I am having some trouble trying to call a JQuery function from multiple images on my page. if someone could help me out that would be great.
This is my code:
HTML
<input type="image" name="rateButton[1]" src="img/Rate1.png" height="40" width="40" value="1" onclick="rateBox(1)"/>
<input type="image" name="rateButton[2]" src="img/Rate2.png" height="40" width="40" value="1" onclick="rateBox(2)"/>
<input type="image" name="rateButton[3]" src="img/Rate3.png" height="40" width="40" value="1" onclick="rateBox(3)"/>
<input type="image" name="rateButton[4]" src="img/Rate4.png" height="40" width="40" value="1" onclick="rateBox(4)"/>
<input type="image" name="rateButton[5]" src="img/Rate5.png" height="40" width="40" value="1" onclick="rateBox(5)"/>
<input type="image" name="rateButton[6]" src="img/Rate6.png" height="40" width="40" value="1" onclick="rateBox(6)"/>
<input type="image" name="rateButton[7]" src="img/Rate7.png" height="40" width="40" value="1" onclick="rateBox(7)"/>
<input type="image" name="rateButton[8]" src="img/Rate8.png" height="40" width="40" value="1" onclick="rateBox(8)"/>
<input type="image" name="rateButton[9]" src="img/Rate9.png" height="40" width="40" value="1" onclick="rateBox(9)"/>
<input type="image" name="rateButton[10]" src="img/Rate10.png" height="40" width="40" value="1" onclick="rateBox(10)"/><br>
JQuery
$(document).ready(function(){
function rateBox(rating){
// Ajax Call here...
}
});
You should move your function outside the
.ready()function as others have suggested.Also the best practice for attaching events to multiple elements is to delegate the event to the parent element. It will attach only one event and listen for events that bubble-up from the selector used. Ex. using JQuery…
In your situation you can add a parent wrapper (with id = “ratings”) and add a class to your rateButtons (class = “rateButton”)
reduced DOM for the sake of clarity.
and then bind the event on parent (outside the ready function of-course)
Example
JQuery
.on()documentaion