I've got a list of possible checkboxes and the user can select up to three options. What I'm struggling with is how to recognize which boxes are checked, and then assign them to variables (to send in a later ajax call). So far the code I've written seems to just take the first three checkbox values regardless of whether they are checked or not and use those in my ajax call. Please help me figure out where I've gone wrong.
Here's my HTML:
<ul id="Names" class="stateNames">
<li>Alabama
<ul class="airports">
<li><input type="checkbox" class="destination"/> Birmingham, AL</li>
<li><input type="checkbox" class="destination"/> Huntsville, AL</li>
</ul>
<li>Alaska
<ul class="airports">
<li><input type="checkbox" class="destination"/> Anchorage, AK</li>
<li><input type="checkbox" class="destination"/> Fairbanks, AK</li>
<li><input type="checkbox" class="destination"/> Juneau, AK</li>
</ul>
</li>
</ul>
<input type="button" onclick="clickHandler()" value="Submit" />
Here's my javascript/jquery:
function clickHandler() {
endLocDest1 = "";
endLocDest2 = "";
endLocDest3 = "";
for(i = 0; i < document.getElementsByClassName('destination').length; i++) {
if (document.getElementsByClassName('destination')[i].checked) {
endLocDest1 = document.getElementsByClassName('destination')[0].value;
endLocDest2 = document.getElementsByClassName('destination')[1].value;
endLocDest3 = document.getElementsByClassName('destination')[2].value;
}
alert(endLocDest1 + endLocDest2 + endLocDest3);
};
}
I've also put this code into a fiddle http://jsfiddle.net/6ywm1n6h/3/ (which currently doesn't return anything).
Thanks in advance!
In your jsfiddle, you had jQuery turned on, assuming that, try using ...
$(".destination:checked")
Which will return all checked; you can use this as an array and determine which are clicked.
EDIT:
You can assign this to a variable, say ...
var checked_values = $(".destination:checked");
... then loop through and do what you need.
for (var i=0,len=checked_values.length; i<len; i++) {
console.log(checked_values[i].attr("id"));
}
If your code is wrapped in <form> and </form> then checked inputs will be sent automatically when form is submitted (normaly or AJAX'ed). Your mistake is that you do not set names nor values to your checkboxes. Try:
<input type="checkbox" name="airport[alabama][]" value="Birmingham">
<input type="checkbox" name="airport[alabama][]" value="Huntsville">
<input type="checkbox" name="airport[alaska][]" value="Anchorage">
<input type="checkbox" name="airport[alaska][]" value="Fairbanks">
and see print_r($_POST) or print_r($_GET) (depending on your form method) in page which receives form submission.
Related
I'm trying to enable/disable an "other" field at the bottom of a set of radio buttons, like so...
window.init = function() {
debugger;
var form = $("#myform");
var enableOther = function() {
var other = $(this).val() == 'other';
form.find('input[name=other]').prop('disabled', !other);
};
var options = form.find('input:radio[name=myradio]');
options.change(enableOther);
//now I want to call the on-change handler to update the initial disabled value
$.proxy(enableOther, options)(); //these don't work
//options.trigger('change');
//options.triggerHandler('change');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="debugger; init();">Init</button>
<form id="myform">
<ul>
<li><input type="radio" name="myradio" value="1" />Item 1</li>
<li><input type="radio" name="myradio" value="2" />Item 2</li>
<li><input type="radio" name="myradio" value="3" />Item 3</li>
<li><input type="radio" name="myradio" value="other" />Other</li>
<li><input type="text" name="other" /></li>
</ul>
</form>
(click Init, select Other, click Init again, and the field incorrectly becomes disabled)
This works fine when clicking through each item, but I want to be able to have my .change() jquery callback trigger once in the init function (this snipped goes into a popup form with persisting values). I've tried .proxy and trigger, but I seem to be getting all radio buttons and .val() is the individual value, not the selected one.
How should I be artificially triggering this callback?
Radio buttons are odd.
In your callback use the selector for the one that is checked.
var myval = $('input[type="radio"][name="myradio"]:checked').val();
var other = myval == 'other';
Note: use [type="radio"] not the :radio as it allows the selector to be more efficient when browsers support that.
Test: to prove the concept, set the OTHER prior to calling the init:
$('input[type="radio"][name="myradio"]').eq(3).prop('checked',true);
and then the one that is NOT:
$('input[type="radio"][name="myradio"]').eq(2).prop('checked',true);
THEN use what you tried:
options.trigger('change');
I have tried several ways to achieve this, but somehow nothing works for this.
How can I copy the "label text" of respective Radio Button, which is selected by user into the input field (Result Box) in real time?
HTML -
<ul class="gfield_radio" id="input_4_4">
Radio Buttons:
<br />
<li class="gchoice_4_0">
<input name="input_4" type="radio" value="2" id="choice_4_0" class="radio_s" tabindex="4">
<label for="choice_4_0">Hi</label>
</li>
<li class="gchoice_4_1">
<input name="input_4" type="radio" value="4" id="choice_4_1" class="radio_s" tabindex="5">
<label for="choice_4_1">Hello</label>
</li>
<li class="gchoice_4_2">
<input name="input_4" type="radio" value="3" id="choice_4_2" class="radio_s" tabindex="6">
<label for="choice_4_2">Aloha</label>
</li>
</ul>
<br />
<div class="ginput_container">
Result Box:
<br />
<input name="input_3" id="input_4_3" type="text" value="" class="medium" tabindex="3">
</div>
My attempts:
$('input').change(function() {
if (this.checked) {
var response = $('label[for="' + this.id + '"]').html();
alert(response);
}
// also this:
// if ($("input[type='radio'].radio_s").is(':checked')) {
// var card_type = $("input[type='radio'].radio_s:checked").val();
// alert('card_type');
// }
});
You need to traverse the DOM from the radio which was clicked to find the nearest label element.
$('.radio_s').change(function() {
$('#input_4_3').val($(this).closest('li').find('label').text());
});
Example fiddle
You could also use $(this).next('label') however, that relies on the position of the label element not changing. My first example means the label can be anywhere within the same li as the radio button and it will work.
Try this:
$('.radio_s').click(function() {
$("#input_4_3").val($("input:checked" ).next().text());
});
Demo: http://jsfiddle.net/WQyEw/3/
This is a slightly tricky question to answer well. The structure of your HTML implies that there may be more than one of these structures on the page. So you may have more than one set of radio buttons with a corresponding checkbox.
I have put some working code into a jsFiddle.
I made one change: all the code you had in your question is now in <div class="container">. You would need as many of these as you had groups of radio buttons and checkboxes.
You can then have jQuery code like this:
$('ul.gfield_radio').on('change', 'input[type="radio"]', function () {
var label = $('label[for="' + this.id + '"]');
$(this).closest('.container').find('input.medium').val(label.text());
});
This code is not tied to the id values in this particular bit of HTML, but would work as many times as necessary throughout the page.
Why to depend on third party library when you can achieve it with plain javascript:
<script>
document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementsByName('input_4');
for (var i = 0; i < a.length; i++) {
document.getElementsByName('input_4')[i].addEventListener('change', function () {
showValue(this);
}, false);
}
}, false);
function showValue(element) {
alert(element.parentNode.getElementsByTagName('label')[0].innerHTML)
}
</script>
I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.
I have a div which contains several radio buttons, like this:
<div name="type" id="type">
<ul class="options-list">
<li>
<input type="radio" name="myname1" value="121312" id="myid1">somevalue
</li>
<li>
<input type="radio" name="myname2" value="121312" id="myid2">somevalue
</li>
</ul>
</div>
Now one of the two is checked, how could I get that one using plain JavaScript or PrototypeJS?
Thanks!
You can use,
if(document.getElementById('myid1').checked){
alert(document.getElementById('myid1').value)
}
if(document.getElementById('myid2').checked){
alert(document.getElementById('myid2').value)
}
Just giving an idea.
Well assuming they all have the same name you could do this:
function getCheckedRadio(rbGroupName) {
var rb = document.getElementsByName(rbGroupName);
for (i = 0; i < rb.length; i++) {
if (rb[i].checked) {
return rb[i].id;
}
}
}
Now you could call this within a click/change event handler to return the ID.
I've made a simple form using Ryan Fait's Custom Form Elements. Now I am trying to implement a "Check All"/"Uncheck All" function.
What I have mostly works, except that the user has to click the buttons twice to get the desired result. I have a feeling that I need to call this function from inside the Custom Form Elements script, but I don't know how.
I'm using JQuery, Custom Form Elements (http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/custom-form-elements.js), and this:
<script type = "text/javascript">
function cboxToggle(group, action) {
for( var i=0, len = group.length; i < len; i++) {
group[i].checked = action;
}
}
</script>
My HTML:
<form name="myname" action="checkboxes.asp" method="post">
<input type = "button" value = " CHECK ALL" onclick = "cboxToggle(check_list, !this.checked)"><br>
<input type = "button" value = " UNCHECK ALL" onclick = "cboxToggle(check_list, this.checked)"><br>
<p><input type="checkbox" name="check_list" value="1" class="styled" />Option 1 </p>
<p><input type="checkbox" name="check_list" value="2" class="styled" />Option 2 </p>
<p><input type="checkbox" name="check_list" value="3" class="styled" />Option 3 </p>
</form>
Any help would be appreciated -- thanks!
If you're using jQuery then why not use it to its full potential? Which also means, no inline code... Add an id to your buttons first. Then make sure you're using groups properly, so instead of group you do group[]. Then use this code and it should work:
var ckToggle = function (group, action) {
$('[name="'+ group +'"]').prop('checked', action)
}
$('#buttonAll').click(function(){ ckToggle('check_list[]', true) })
$('#buttonNone').click(function(){ ckToggle('check_list[]', false) })
Check out the following URL
Uncheck checkbox in custom form elements