Agnes Leung Agnes Leung -4 years ago 90
HTML Question

Elements chosen have same value but different id

How can I choose to run the same function with different parameters according to the id?

In the JQuery, the input buttons with

value="+"
is chosen, then I want to determine what is their id, and then call the javascript function with different parameters.

For example, button with
id="Add_1"
is chosen, then the function called is
getData(0);


Here is the html (extract)

<html>
<head>
<link href="../css/coin_convert.css" rel="stylesheet" type="text/css">
<script src="coin_convert.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="form">
<form name="coins">
<input type="button" value="+" id="Add_1" />
<input type="button" value="+" id="Add_2"/>
<input type="button" value="+" id="Add_3"/>
<input type="button" value="+" id="Add_4"/>
</form>
</div>


</body>
</html>


Here is the JQuery

$(document).ready(function() {
$("[value='+']").on("click", function() {
if($("[value='+']").is("Add_1")){
getData(0);
}
});
});


Here is the JavaScript function to be called

function getData(n){
var coin = new Array(4);
switch (n){
case 0:
coin[n]=document.getElementById('coin_dragon').value;
break;
case 1:
coin[n]=document.getElementById('coin_sky').value;
break;
case 2:
coin[n]=document.getElementById('coin_special').value;
break;
case 3:
coin[n]=document.getElementById('coin_legend').value;
break;
}
addition(coin[n]);

}


Many thanks!

Answer Source

You need to use .attr('id') to find the ID attribute.

In order to have this run for each element that has the associated ID, you would need to run a loop that uses an index, and gets the data based off of that index:

$(document).ready(function() {
  $("[value='+']").each(function(index) {
    $(this).click(function() {
      if ($(this).attr('id') == 'Add_' + (index + 1)) {
        getData(index);
      }
    });
  });
});

In this example, whenever an element with both a value of + and an ID that starts with Add_ is clicked, getData() will trigger, passing through one less than the the number in the element's ID. Clicking an element with an ID that doesn't start with Add_ will not trigger getData().

I've created a working fiddle showcasing this here.

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download