Fix JS code: Append multiple values out of checkboxes to url - javascript

I found this code that replaced the link text (= "Show") by the checked checkbox values. Now, I am looking for a code that appends/removes the checked/unchecked values to the link url itself.
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
return +e.value;
});
$("[href$='feature=']").text('the checked values are: ' + arr.join(','));
}
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
<div>Show</div>
Show
Thank you very much for your help, guys!

I would use an .each() loop instead of $.map()...
Also, since you wish to change the href... And that it is used with an attribute selector, I would save the element in a variable before the href changes. And the same for the href "base" value itself. Because on second click, the href will not end in feature=.
So here is a working demo:
function calculate() {
var arr = [];
$('input:checkbox:checked').each(function(i,v) {
arr.push(v.value);
});
// The array in console
console.log(arr);
// Join it has a string
var arr_string = arr.join(",");
// Use the string in the link's text AND the href
link
.text('the checked values are: ' + arr_string)
.attr('href', link_href_base + arr_string);
// The link's href in console
console.log(link.attr("href"));
}
// Variables that won't change
var link = $("[href$='feature=']");
var link_href_base = link.attr("href");
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
<div>Show</div>

Related

Removing from array values of checkboxes in jQuery

I have a checkboxes like this:
while($userRow=$resultForUsers->fetch_assoc()){
$nameOfUser=$userRow['users_name'];
$userId=$userRow['user_facebook_id'];
$userFBPicture=$userRow['users_picture'];
echo "
<tr class='tr-data-users'>
<td class='text-center'>
<input type='checkbox' class='checkbox' onclick='if(this.checked){selo(this.value)}else{izbaci(this.value)}' value=$userId>
</td>
So, for each user in my database I'm having one checkbox with value of his id. I need id's of all checked users(i.e checkboxes) in one array. I did it this way:
<input type='checkbox' class='checkbox' onclick='if(this.checked){put(this.value)}else{remove(this.value)}' value=$userId>
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
}
So, console.log now displays id's of all checked checkboxes. What I want to do is if checkbox is unchecked then to remove that id(i.e chechbox value) from array. I tried it like this:
onclick='if(this.checked){put(this.value)}else{remove(this.value)}'
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
remove(o,niz);
}
function remove(o,niz){
if($.inArray(o,niz)){
console.log('radim');
var indexNiza= $.inArray(o,niz);
niz= $.grep(niz,function(a,o){
return (a!=o);
});
}
}
As you can see this else part should handle if checkbox is unchecked and remove that id from array, but it doesn't work. Would really appreciate help on this.
It seems that the code you have written is taking a very complex route for a simple job. You can see the following for a good example on how to obtain all of the values into their own arrays for the checked and unchecked states.
In the demonstration, I enumerate through the checked and unchecked checkboxes if the user changes the state of any checkbox, and store the checked values in an array named cbChecked and the unchecked values get stored in cbUnchecked
The key here is the selectors used:
Selector usage
Get all 'checked' objects
:checked
Get all 'unchecked' objects
:not(:checked)
Demonstration
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
var cbChecked = new Array();
var cbUnchecked = new Array();
$("input[type='checkbox']:checked").each(function() {
cbChecked[cbChecked.length] = this.value;
});
$("input[type='checkbox']:not(:checked)").each(function() {
cbUnchecked[cbUnchecked.length] = this.value;
});
$("p#cbChecked").html( cbChecked.join() );
$("p#cbUnchecked").html( cbUnchecked.join() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> The checkbox form</h2>
<form id="foo">
<p>A : <input type="checkbox" id="a" value="a"></p>
<p>B : <input type="checkbox" id="b" value="b"></p>
<p>C : <input type="checkbox" id="c" value="c"></p>
<p>D : <input type="checkbox" id="d" value="d"></p>
<p>E : <input type="checkbox" id="e" value="e"></p>
<p>F : <input type="checkbox" id="f" value="f"></p>
</form>
<h2>Checked Values</h2>
<p id="cbChecked"></p>
<h2>Unchecked Values</h2>
<p id="cbUnchecked"></p>

Get output of .change() function in .click() function

I have two radio buttons which both have values. When one is selected, and a button/link is clicked, the value of the selected radio button needs to be outputted to a text box.
Here is my HTML:
<form class="discount-choice" method="post" action="#">
<ul>
<li>
<input type="radio" value="1" name="discount" id="1-month" class="discount-checkbox" />
<label for="1-month">1 Month - no discount</label>
</li>
<li>
<input type="radio" value="0.95" name="discount" id="4-months" class="discount-checkbox" />
<label for="4-months">4 months - 5% discount</label>
</li>
</ul>
Get Result
<input type="text" class="result" />
</form>
and my JavaScript (jQuery):
var discount = $(".discount-checkbox").on("click", function () {
return this.value;
});
$(".get-result").on("click", function() {
$(".result").attr("value", discount);
});
When I click the button (after having selected a radio button), I just get [object Object] in the text box.
I'm not sure of the syntax for setting a variable to be a jQuery function so this is likely where I am going wrong. If anyone could give me some guidance that would be awesome.
Thank you for any help :)
discount is set to the jQuery object returned by $(".discount-checkbox"). You need to bind a click handler that updates a variable:
var discount = 0;
$(".discount-checkbox").on("click", function () {
discount = this.value;
});
Use this:
$(".get-result").on("click", function(e) {
e.preventDefault();
$(".result").val( $('.discount-checkbox:checked').val() );
});
You do not need the click handler on the checkbox as #billyonecan has mentioned in the comments.
And ... if you really need to attach an event handler to the checkboxes, that would be a change event handler instead of click.
Try This Code:
var discount;
$(".discount-checkbox").on("click", function () {
discount= this.value;
});
$(".get-result").on("click", function() {
$(".result").attr("value", discount);
});
no need of discount-checkbox click event
$(".get-result").on("click", function() {
var discount = $(".discount-checkbox:checked").val();
$(".result").val(discount);
});

validating at least one checkbox selected on dynamically added fields

If you're dynamically adding form fields to an existing form, what's the best way of adding validation?
Consider this fiddle: http://jsfiddle.net/yWGK4/
<form action="#" method="post">
<div id="parent">
<div class="child">
<input type="checkbox" name="box1[]" value="1" /> 1
<input type="checkbox" name="box1[]" value="2" /> 2
<input type="checkbox" name="box1[]" value="3" /> 3
</div>
</div>
</form>
<button id="addBoxes">Add Boxes</button>
<script>
$(function() {
var parentdiv = $('#parent');
var m = $('#parent div.child').size() + 1;
$('#addBoxes').on('click', function() {
$('<div class="child"><input type="checkbox" name="box'+m+'[]" value="1" /> 1 <input type="checkbox" name="box'+m+'[]" value="2" /> 2 <input type="checkbox" name="box'+m+'[]" value="3" /> 3 </div>').appendTo(parentdiv);
m++;
return false;
});
});
</script>
On that form I'm adding new checkbox groups, and want to make sure at least one box from each group is checked (not one box across all groups). Anyone got any clever methods? Everything I've looked at would get very complicated due to the dynamically added fields.
It doesn't matter if the checkboxes are dynamic when validating on submit etc. so something like this would check if at least one checkbox per .child is checked :
$('form').on('submit', function(e) {
e.preventDefault();
var valid = true;
$('.child').each(function() {
if ( ! $('[type="checkbox"]:checked', this).length ) // no box checked
valid = false;
});
if (valid) {
this.submit();
}else{
alert('error');
}
});
FIDDLE
If you want to check it using jQuery you can use `.each()
$(".child").each(function(){
var $this = $(this);
var checked = $this.find("input:checked");
if( checked.lenght == 0 ) {
alert("This group is not valid");
}
});
You can find more about this jQuery functions in this links:
each()
find()
here's what I came up with. Basically you loop over the .child groups and test if they have a checkbox in the checked state..
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});

Show element with attribute

<input type="radio" name="group2" test="one" value="Water"> Water
<input type="radio" name="group2" test="two" value="Beer"> Beer<br>
<div style="display: none" test="one">aaaaaaa</div>
<div style="display: none" test="two">bbbbbbb</div>
<div style="display: none" test="one">ccccccc</div>
I would like: if i click on radio Water with attribute test="one" then should show me all div with attribute test="one". How can i make it with jQuery?
LIVE: http://jsfiddle.net/hRCXV/
Try this:
$("input[type='radio']").click(function() {
var test = $(this).attr("test");
$("div[test]").hide();
$("div[test='" + test + "']").show();
});
Updated fiddle
Please bear in mind that creating your own attributes as you have here is not valid. If you're using HTML5 you should consider using the data attribute to store whatever information you need associated with each element.
Attach a label to the Water text, and a click handler using the attribute selector:
<label for="option1">
<input type="radio" name="group2" id="option1" test="one" value="Water"> Water
</label>
<script>
$('label').click(function() {
// Logic tells me that you want to only show the test elements whose
// attribute matches the selected radio element; Hide the previous ones:
$('div[test]').hide();
// Get test value:
var test = $('#' + $(this).attr('for') ).attr('test');
$('div[test="' + test + '"]').show();
});
</script>
$('input [value="Water"]').click(function() {
$('[test="one"]').show();
});
jsFiddle: http://jsfiddle.net/hRCXV/1/
$("input[type=radio][value=Water]").click(function()
{
$("[test=one]").show();
});​
I belive this is something that you are looking for?
​$(':radio[name="group2"]')​.click(function(e){
var test = $(this).attr('test');
$('div[test]').hide();
$('div[test='+test+']').show();
});​
try this
jQuery(document).ready(function(){
var yourAttributeName = 'test';
var allDivs = jQuery('div['+yourAttributeName+']');
jQuery('input['+yourAttributeName+']').click(function(){
allDivs.hide().filter('[' + yourAttributeName + '=' + jQuery(this).attr(yourAttributeName) + ']').show();
})
//check the init checked
.filter(':checked')
//and fire click event to filter
.click();
});

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources