Jump to content

Find any selected radio/checkbox


Spunky

Recommended Posts

I have a mixture of several checkboxes and groups of radio buttons and each of them have their own number value that we will call points. Anytime that a radio or checkbox is checked I want the value to be added to a total, to get total number of points. I know I can make an if statement that identifies when/if each one is checked and then identifies the value of that specific one..but that is redundant..although simple enough. Nevertheless I ran across some JQuery that allows you to check if any radio or checkbox has been checked which is great but then I'm not sure how to branch from that and get the value of it.

$("#check1").click(function(){    if($('input[type=radio]:checked').length == 0){	   alert("Please select one radio");    }})$("#check2").click(function(){    if($('input[type=checkbox]:checked').length == 0){	   alert("Please select minimum one checkbox");    }})

Basically needing to find the value of the radio/checkbox that has been clicked and utilize it. Is this possible?

Link to comment
Share on other sites

When I was using an event handler to run a function onclick for the checkbox (which would require putting onclick in each one) I got this code to work:

function checkChecked(){     alert($('input[type=checkbox]:checked').val()); }

but I instead would like something more like:

$("input").click(function() {alert($('input[type=checkbox]:checked').val());});

But nothing is happening. I tried putting it inside a function with event handler just to make sure maybe it is never finding the code but the function should bring notice to it. It enters the function but still does nothing with the $("input").click(function(). Any suggestions?EDIT: Further testing reveals that if I click the checkbox again (unchecking it) it alerts 'undefined' twice, checking it again alerts the value 3 times..unchecking alerts 'undefined' 4 times..checking again alerts the value 5 times...so on and so forth..I'm confused.

Edited by Spunky
Link to comment
Share on other sites

See my EDIT I put in before I saw this reply. :) The JavaScript console isn't even showing anything to give me anything to go off of. As I said, with the function running the code, the val() method works, it alerts the value as expected (though now I dont know what happens if I click it a second time). EDIT: The function makes it work fine. The only flaw is that since it is an onclick event handler it tries to alert a value that doesn't exist. So maybe just the code floating by itself it isn't reaching it correctly. But I don't understand why it alerts multiple times.

Edited by Spunky
Link to comment
Share on other sites

If it keeps adding to the number of times it runs then that sounds like you are assigning a click handler inside another click handler, so that each time it gets clicked you add another handler.

Link to comment
Share on other sites

Ok here is the two things I have tried:

$("input").click(function() {alert($('input[type=checkbox]:checked').val());});

This code is standing alone in the JavaScript file, I realize this is dangerous and maybe I should put it in a function that runs when the body loads..I just haven't quite figured it out. And that could be why it is messing up. What happens is, the first time I select the checkbox, nothing happens. The 2nd time I click the checkbox, it alerts undefined twice..the 3rd time it alerts the value set in the checkbox 3 times. So on so on. This is the other code I have tried...I put an event handler in the checkbox for onclick="checkChecked()l":

function checkChecked(){alert($('input[type=checkbox]:checked').val());}

This works perfectly. Only, I do not want to put an event handler in every single checkbox and radio button. Instead, I want it to detect anytime one is clicked and then I will handle it. The first code does this..it is just buggy. I did a bit more testing on it. In the html body I put an onclick event handler to run the function checkChecked() that looks like this:

function checkChecked(){("input").click(function() {alert($('input[type=checkbox]:checked').val());});}

When the page loads I get this error: Uncaught TypeError: Object input has no method 'click' There is alternative code that I tried using:

function checkChecked(){$( "input" ).on( "click", function() {alert($('input[type=checkbox]:checked').val());});}

But I would get this error: Uncaught TypeError: Object [object Object] has no method 'on' To which I then read that code is for a newer version so I must be using an older one. I don't know. Now neither seem to be working... I hope this clears up the code I am using and how I know I was getting confusing before.

Link to comment
Share on other sites

If your checkChecked function is an event handler then that's the problem with duplication, every time you run that event handler you assign an event handler to the checkbox. It doesn't show anything the first time because the first time you just assign the event handler. The second time it runs the first event handler and then assigns another one. Then it runs both event handlers and assigns a third, etc. Don't assign an event handler inside another event handler, that's why it is doing that. Assign the event handlers in a function that runs when the page loads, don't keep assigning new event handlers every time you click.

Link to comment
Share on other sites

$('input[type=checkbox], [type=radio]').change(function() // identify if chbox or radio has been changed{var InputValue=0;$('input[type=checkbox]:checked, [type=radio]:checked').each(function(){ //loop through each chkbox and radio that has been selected to retrieve value and add togetherInputValue = parseInt(InputValue)+parseInt($(this).val());});alert(InputValue) //output final result});});

Link to comment
Share on other sites

$("input").click(function() {alert($('input[type=checkbox]:checked').val());});

This code is standing alone in the JavaScript file, I realize this is dangerous and maybe I should put it in a function that runs when the body loads..I just haven't quite figured it out. And that could be why it is messing up. What happens is, the first time I select the checkbox, nothing happens. The 2nd time I click the checkbox, it alerts undefined twice..the 3rd time it alerts the value set in the checkbox 3 times. So on so on.

If your checkChecked function is an event handler then that's the problem with duplication, every time you run that event handler you assign an event handler to the checkbox. It doesn't show anything the first time because the first time you just assign the event handler. The second time it runs the first event handler and then assigns another one. Then it runs both event handlers and assigns a third, etc. Don't assign an event handler inside another event handler, that's why it is doing that. Assign the event handlers in a function that runs when the page loads, don't keep assigning new event handlers every time you click.
What I quoted from my post is where I am having the issues of multiple alerts. There is no event handler for that code. As stated, it is standing alone, runs when it detects. I made that post to try to clear that up, justsomeguy. Hope that is clear now.
Link to comment
Share on other sites

$('input[type=checkbox], [type=radio]').change(function() // identify if chbox or radio has been changed{var InputValue=0;$('input[type=checkbox]:checked, [type=radio]:checked').each(function(){ //loop through each chkbox and radio that has been selected to retrieve value and add togetherInputValue = parseInt(InputValue)+parseInt($(this).val());});alert(InputValue) //output final result}); });

I tried putting this code standalone and in a function that runs when the body loads and nothing is happening, not even any errors. However, this seems like it would be doing exactly what I need. Would it add the values as the checkboxes/radio buttons are being pressed or would it require a button being pressed after all selections are checked? I haven't yet made it this far, having only been trying to retrieve the values, but my end goal is for it to add and subtract the values as they are being checked and unchecked.
Link to comment
Share on other sites

There is no event handler for that code. As stated, it is standing alone, runs when it detects. I made that post to try to clear that up, justsomeguy. Hope that is clear now.
How else would you explain the fact that an additional event handler apparently gets added each time you click on the element? I've seen this issue several times, and the answer is always because an event handler is being attached inside another handler. Do you have an example of this online? Obviously individual code segments aren't giving us the entire picture.
Link to comment
Share on other sites

Yes, any radio or checkbox that is selected triggers it look at ALL checkboxs and radio buttons that have been selected/checked and add these values together as it loops through them.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script><script type="text/javascript">/*<![CDATA[*//*---->*/$(function()    {    $('input[type=checkbox], [type=radio]').change(function()        {        var InputValue=0;        $('input[type=checkbox]:checked, [type=radio]:checked').each(function()            {            InputValue = parseInt(InputValue)+parseInt($(this).val());            });        //alert(InputValue)        $('#total span').html(InputValue);        });    });/*--*//*]]>*/</script><style type="text/css">#total {border:1px solid #000; float:left; width:100px; margin: 20px; padding:5px;}</style></head><body><form action="" method="post"><input type="radio" name="buztype" value="0" checked="checked"><label>0</label> <br>  <input type="radio" name="buztype" value="8"><label>8</label> <br>  <input type="radio" name="buztype" value="1"><label>1</label><br>  <input type="radio" name="buztype2" value="0" checked="checked"><label>0</label> <br>    <input type="radio" name="buztype2" value="5"><label>5</label> <br>  <input type="radio" name="buztype2" value="3"><label>3</label><br>   <input type="checkbox" name="addthis" value="2" /><label>2</label><br />    <input type="checkbox" name="addthis" value="4" /><label>4</label><br />      <input type="checkbox" name="addthis" value="-6" /><label> - 6</label><br />		    </form><div id="total">Total: <span> </span></div></body></html>

Edited by dsonesuk
Link to comment
Share on other sites

How else would you explain the fact that an additional event handler apparently gets added each time you click on the element? I've seen this issue several times, and the answer is always because an event handler is being attached inside another handler. Do you have an example of this online? Obviously individual code segments aren't giving us the entire picture.
It's the only code segment actually. Except for the radio buttons and checkboxes in the HTML. Would you like to see the onclick event handler I place in the body that runs the function for the other code I've tried? I figured that part was pictured well enough in the mind. Notice in my last larger post where I state when I use an event handler that is when the code works the best and closest to what I need. Actually exactly what I need except I don't want it done in an event handler for everytime the checkbox or radio button is clicked.
Link to comment
Share on other sites

dsonesuk, as I said, I implemented the code and it isn't doing a single thing. Not alerting anything or giving any errors. I even put in

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>

Just incase I am not using the correct version of JQuery and I have put in the form you created. The radio buttons and checkboxes I am using are all dynamically put into the HTML so I just want to make sure the code is meshing okay. But everything seems in check and still nothing is occuring. I can show you all of my code but it is a little confusing.

<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="warhammerFunctions.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script><title>Untitled Document</title></head><body [color=#0000ff]onLoad="armySelect()[/color];"><span>Warhammer</span><span id="userArmy"></span> <span id="armyPoints"></span><span id="instructions"><strong></strong></span>   <p id="mainArea">	  	</p></body></html>

The main area is where the text is dynamically being changed.

function armySelect(){document.getElementById("instructions").innerHTML = "Select Army:";document.getElementById("mainArea").innerHTML = armySelectOptions();}

armySelect() is running from the onload event handler in the body.

function armySelectOptions(){return "<select id='selectArmy' onChange='pointSelect();'>";}

mainArea is then replaced with code in armySelectOptions() I won't show all of it to keep it minimal, but it does replace it with new code from pointSelect().And then replaced again with new code from another function until we finally reach the function that replaces the html with the checkboxes and radio buttons:

function WoodElfUnits(){return WoodElfUnits = "<span>With a " + armyPoints + " points army, you must follow the following specifications for your army: <ul><li>Lords Units: " + lordsUnits + "</li><li>Heroes Units: " + heroesUnits + "</li><li>Core Units: " + coreUnits + "</li><li>Special Units: " + specialUnits + "</li><li>Rare Units: " + rareUnits + "</span><span id='lords'>Lords</span><table id='WoodElfHighborn' class='unitTitle'><caption>Wood Elf Highborn (+145pts/model)<input type='checkbox' name='Wood Elf Highborn' value='145' id='selectWoodElfHighborn' onclick='selectWoodElfHighborn();'> <span id='WEHmodelNumber'></span></caption><tr><td>M</td><td>WS</td><td>BS</td><td>S</td><td>T</td><td>W</td><td>I</td><td>A</td><td>Ld</td></tr><tr><td>5</td><td>7</td><td>6</td><td>4</td><td>3</td><td>3</td><td>8</td><td>4</td><td>10</td></tr></table><span id='WandA'>Weapons & Armour: Longbow</span><span>Options</span><ul><li>May choose an additional hand weapon (+6pts) <input type='radio' name='WEH1stOption' value='6' id='WEHhandWeapon'>, a spear (+3pts) <input type='radio' name='WEH1stOption' value='3' id='WEHspear'> or a great weapon (+6pts)<input type='radio' name='WEH1stOption' value='6' id='WEHgreatWeapon'></li><li>May wear light armour (+3pts)<input type='checkbox' name='WEH2ndOption' value='3' id='WEHlightArmour'>, and may carry a shield (+3pts)<input type='checkbox' name='WEH2ndOption' value='3' id='WEHshield'></li><li>May be a member of one of the following Kindreds: Wardancer (+50pts)<input type='radio' name='WEH3rdOption' value='50' id='WEHwardancer' onclick='selectWEHwildRider();'>, Wild Rider (+50pts)<input type='radio' name='WEH3rdOption' value='50' id='WEHwildRider' onclick='selectWEHwildRider();'>, Waywatcher (+45pts)<input type='radio' name='WEH3rdOption' value='45' id='WEHwaywatcher' onclick='selectWEHwildRider();'>, Alter (+35pts)<input type='radio' name='WEH3rdOption' value='35' id='WEHalter' onclick='selectWEHwildRider();'>, Scout (+25pts)<input type='radio' name='WEH3rdOption' value='25' id='WEHscout' onclick='selectWEHwildRider();'> or Eternal (+10pts)<input type='radio' name='WEH3rdOption' value='10' id='WEHeternal' onclick='selectWEHwildRider();'></li><ul><li>If a member of a Wild Rider Kindred, may also ride a Great Stag (+50pts)<input type='checkbox' name='WEH4thOption' value='50' id='WEHgreatStag' disabled='disabled'></li></ul><li>May ride either an Elven Steed (+18pts)<input type='radio' name='WEH5thOption' value='18' id='WEHelvenSteed'>, a Great Eagle (+50pts)<input type='radio' name='WEH5thOption' value='50' id='WEHgreatEagle'> or a Forest Dragon (+320pts)<input type='radio' name='WEH5thOption' value='320' id='WEHforestDragon'></li><li>May choose Spites and/or items from the Common or Wood Elf Magic Item lists with a maximum total value of 100pts</li></ul><span id='totalPoints'></span>";}

Unfortunately all the html code has to be squished together. It's just a simple program though for my own use, not a big deal. But that is the code that I am trying to make the JQuery mingle with. I have other JavaScript that mingles with it just fine so I'm just unsure what is going on, but I am not as familiar with JQuery.

Link to comment
Share on other sites

try
$('input[type=checkbox], [type=radio]').live('change', function()

instead of

$('input[type=checkbox], [type=radio]').change(function()

Thank you this made it work peerrrrfectly. It adds them up and every time I check a new one a new alert tells me the total. Perfect.
calling a function as you did
function checkChecked(elem)	{	if($(elem).is(':checked'))	{	alert($(elem).val());	}	}

<input type="checkbox" name="addthis" onclick="checkChecked(this)" value="-6" /><label> - 6</label><br />

I'm not sure what this code was for, but I don't want to have to put an onclick event control in every single radio button and checkbox in order to check for it..that is what I am avoiding. But the other code works perfect, I should be able to tweak that no problem to do what I want (instead of alert) now that I have it getting the values and adding them, thank you!
Link to comment
Share on other sites

I've been using the same JQuery file for years and did not even think about newer versions coming out. But you're right, I must be using a very older version because the original code I found that lead me to try to do this was:

$( "input" ).on( "click", function() {  $( "#log" ).html( $("input:checked").val() + " is checked!" );});

and I had to do research to find out why my browser error console was telling me there was no .on method and that's when I discovered I should use this instead:

$("input").click(function() {alert($('input[type=checkbox]:checked').val());});

.click I would much prefer to be using up-to-date code. I went to that link you provided and using it I attempted to fix my code (as well as downloaded the lasted version of JQuery) and I cannot get anything to work. The code you had me use that works with my older version of JQuery is here:

$('input[type=checkbox], [type=radio]').live('change', function() // identify if chbox or radio has been changed{var InputValue=0;$('input[type=checkbox]:checked, input[type=radio]:checked').each(function(){ //loop through each chkbox and radio that has been selected to retrieve value and add togetherInputValue = parseInt(InputValue)+parseInt($(this).val());});document.getElementById('playerPoints').innerHTML=(InputValue); //output final result});

And I know the .live needs to be changed to .on but by the syntax there must be something else that needs changing. That page gives examples of .live but not .on. Could you help me out? Also, this simple JQuery code makes me want to use less strictly JavaScript since they seem to have a nice alternative to document.getElementById() and I'm sure other things I am using. Would I select a specific radio/checkbox similarly to how an HTML tag is selected in an example code I have above? How might I target a specific name (set).?

Link to comment
Share on other sites

Sure does. But I can't get it to work. Again I ask, help please?

$('input[type=checkbox], [type=radio]').on('click', function() // identify if chbox or radio has been changed{var InputValue=0;$('input[type=checkbox]:checked, input[type=radio]:checked').each(function(){ //loop through each chkbox and radio that has been selected to retrieve value and add togetherInputValue = parseInt(InputValue)+parseInt($(this).val());});document.getElementById('playerPoints').innerHTML=(InputValue); //output final result});

That is what I managed. Nothing happens when I click the items, no errors or anything. I even tried putting an alert in the first function to see if it is entered but it isn't. Thank you.

Edited by Spunky
Link to comment
Share on other sites

I suppose you DID place the code in the $(function() { }); if not, when the code is reached it tries to apply the code to the targeted element, but the element has not rendered yet! so it can't see it to apply it, inserting in above forces it to wait until the page and therefore ALL targeted inputs are rendered before applying event and the code that goes with it. below works for me, 'click' or 'change'.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> OLD VERSION --><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script><script type="text/javascript">/*<![CDATA[*//*---->*/$(function()    {        $('input[type=checkbox], [type=radio]').on('change', function()        {        var InputValue=0;        $('input[type=checkbox]:checked, [type=radio]:checked').each(function()            {            InputValue = parseInt(InputValue)+parseInt($(this).val());            });        //alert(InputValue)        $('#total span').html(InputValue);        });        	    });    /*--*//*]]>*/</script><style type="text/css">#total {border:1px solid #000; float:left; width:100px; margin: 20px; padding:5px;}</style></head><body><form action="" method="post"><input class="formBuzType" type="radio" name="buztype" value="0"><label>0</label> <br>  <input class="formBuzType" type="radio" name="buztype" value="8"><label>8</label> <br>  <input class="formBuzType" type="radio" name="buztype" value="1"><label>1</label><br>  <input class="formBuzType" type="radio" name="buztype2" value="0"><label>0</label> <br>    <input class="formBuzType" type="radio" name="buztype2" value="5"><label>5</label> <br>  <input class="formBuzType" type="radio" name="buztype2" value="3"><label>3</label><br>   <input type="checkbox" name="addthis" value="2" /><label>2</label><br />    <input type="checkbox" name="addthis" value="4" /><label>4</label><br />     <input type="checkbox" name="addthis" value="-6" /><label> - 6</label><br />      <!--<input type="checkbox" name="addthis" onclick="checkChecked(this)" value="-6" /><label> - 6</label><br />-->		    </form><div id="total">Total: <span> </span></div></body></html>

Link to comment
Share on other sites

With my code before when using the older JQuery and .live it was working without that extra function. I tried it though and still nothing is happening.

$(function(){$('input[type=checkbox], [type=radio]').on('change', function(){  alert('enter');  var InputValue=0;  $('input[type=checkbox]:checked, input[type=radio]:checked').each(function(){   InputValue = parseInt(InputValue)+parseInt($(this).val());  });  $('#playerPoints').html(InputValue);});});

The version JQuery I am using now is 2.0.1:

<script type="text/javascript" src="jquery-2.0.1.min.js"></script>

This code should work for a version later than 1.91 right? I'm going to try to paste your code in a separate document and see if I can get something working. Maybe I have something else going awry I got to figure out.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...