I need to pass two different values back as the result from one checkbox. I tried an object, but the result was undefined (the code works with one value).
' <input type="checkbox" id="cat" value="'+{value1: data.blue, value2: data.red} +'"/>'
result.value1 is always undefined, whereas result works for just a string.
What is the best way to do this using javascript/jquery.
You can use attr for add more values, for example:
<input type="checkbox" id="cat" data-value1="blue" data-value2="red" value=""/>
Get values using jQuery, use:
$("#cat").data("value1");//return 'blue'
$("#cat").data("value2");//return 'red'
Result: https://jsfiddle.net/cmedina/a0ya5bwp/
Why not create a string with a separator
Something like
value1 \t value2
And you just have to search for this separator and cut the string to get your 2 differents values?
You can stringify the object and put that value on the input as a data attribute, in the input change handler, parse the string to JSON.
HTML
<input type="checkbox" id="cat" name="cat">
<label for="cat">Cat</label>
Javascript
var input = document.getElementById('cat');
var testValue = {value1: 'blue', value2: 'red'};
input.setAttribute('data-value',JSON.stringify(testValue));
input.addEventListener('change', function(event) {
var inputValue = JSON.parse(event.target.getAttribute('data-value'));
console.log(inputValue);
});
Demo : JSFiddle
it looks like you have a spelling mistake : vaule1 should be value1
Related
I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });
I have a checkbox having value attribute as shown below :
<input type="checkbox" class="skis checkbox" name="skis" value="hi?hello?Good">
When I am clicking this particular checkbox i want to get the value of this checkbox separately in three different JavaScript variables as hi, hello, Good and should check with ? delimiter in jQuery. Can anyone say how to do this in JavaScript ?
You don't need jQuery for this. To split the string, you can just use .split() function with the parameter being the question mark. All the values will be stored as an array and you can access the first two words using the array index.
$(function () {
$("input").click(function () {
var values = this.value.split("?");
console.log("First word: " + values[0]);
console.log("Second word: " + values[1]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="skis checkbox" name="skis" value="hi?hello?Good">
Use this javascript code.
$(function(){
$('input.checkbox').on('click',function(){
var val=this.value.split('?');
var first=val[0];
var second=val[1];
var third=val[2];
debugger;
});
});
Use .split function to split string on every delimiter:
<input
type="checkbox"
class="skis checkbox"
name="skis"
value="hi?hello?Good"
onClick="console.log(this.value.split('?'))"
/>
I am trying to get an elements id from another elements value and I just keeps returning null. Clicking on the first check box should show what the issue is that I am having.
<input id="test" type="checkbox" name="checkAddress" onclick="checkAddress(this)" value="66" />
<input id="rrrr66" type="checkbox" name="checkAddress" onclick="checkAddress(this)" value="33" />
<script>
function checkAddress(checkbox) {
if (checkbox.checked) {
var testing = '"rrrr'+document.getElementById("test").value+'"';
alert(typeof testing); **<-- shows the correct type**
alert(testing); **<-- shows the correct value**
alert(document.getElementById(testing)); **<-- does not work**
alert(document.getElementById("rrrr66")); **<--works**
}
}
Demo Of issue
Remove the quotation marks from the string:
var testing = 'rrrr'+document.getElementById("test").value;
Quotation marks are for the parser to indicate a string literal. The quotation marks are not actually part of the value. What you are currently doing is equivalent with
document.getElementById('"rrrr66"')
Compare these two outputs:
console.log("foo bar"); // foo bar
console.log('"foo' + ' bar"'); // "foo bar"
1
Get the value of test and add rrrr before:
var testing = "rrrr"+document.getElementById("test").value;
2 Do the trick
document.getElementById(testing)
This should work.
I have check boxes whose value i need to formate into query to send it to server side o button click..If the checkbox is checked i need to add it into query var else ignore ..
Here is my query syntax ..
and toc='local' or toc='isd' .
Here is my code in html..
<input type="checkbox" name="CallTypeLOCAL" id="local" value="'LOCAL'"/>LOCAL</label>
<input type="checkbox" name="CallTypeSTD" id="std" value="'STD'"/>STD</label>
<input type="checkbox" name="CallTypeISD" id="isd" value="'ISD'"/>ISD</label>
<input type="checkbox" name="CallTypeINETCALL" id="inetcall" value="'INETCALL'"/>INETCALL</label>
<input type="checkbox" name="CallTypeINCOMING" id="incoming" value="'INCOMING'"/>INCOMING</label>
Any help will be welcomed..
Thanks in advance..
An elegant way to accomplish this is to combine the checked values into a bitfield. I have done this in this fiddle. The key is writing a little boolean prototype extension to convert bools to integers and then left shift the result as required
Boolean.prototype.intval = function(places)
{
places = ('undefined' == typeof(places))?0:places;
return (~~this) << places
}
With that done you simply do
var rslt = $('#local').is(':checked').intval();
rslt += $('#std').is(':checked').intval(1);
rslt += $('#isd').is(':checked').intval(2);
rslt += $('#inetcall').is(':checked').intval(3);
rslt += $('#incoming').is(':checked').intval(4);
How about something like this?
$("input[type='checkbox']:checked").serialize();
That would work to get the name value pair of all your checkboxes that are checked.
But why not give all these checkboxes the same class? This way you can do something like this (assuming you gave them all class=someData):
$(".someData:checked").serialize();
Also are they enclosed in a form? Then you can just serialize the entire form and it'll be properly encoded and added to the post data
Here's a little fiddle
I have array of checkboxes like below,
<input type="checkbox" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="checkbox" value="1" id="a_r_id[2]" name="a_r_id[2]">
<input type="checkbox" value="1" id="a_r_id[3]" name="a_r_id[3]">
<input type="checkbox" value="1" id="a_r_id[4]" name="a_r_id[4]">
in my page... and i want to submit only the checked one via JavaScript (jQuery AJAX)... how can i do that ?
EDITED :
Actually, i want to get all array keys on the checked checkbox so that i can post it via ajax. Something like "1,4" as a string.
var keys = [],
keystring;
$('input[name^="a_r_id"]:checked').each(function () {
keys.push($(this).attr('name').replace(/a_r_id\[(\d+)\]/, '$1'));
});
keystring = keys.join();
Of course, there are better ways of doing this, but this answers your question as you've framed it.
Finally, i found an answer for my question above. I'll write it down right here.
Problem :
how can i get "key" from array HTML element(s) ? (in my case, only checked checkbox i want to get)
my answer code is something like this :
//first, i get every checked checkbox using jQuery selector,
//as mentioned by DerekHenderson.
var list_agent = $('input[name^="a_r_id"]:checked');
var l_c_agent = new Array();
//then, i create a loop to loop each object returned.
for(var i=0;i<list_agent.length;i++){
//after that, i'm using Regular Expression ( match() ) on every returned object id and throw it into some array.
l_c_agent[i] = list_agent[i].id.match(/[0-9]+/);
}
//finally, i join the array using javascript join() method so that i can pass it using jQuery AJAX as a string to my controller and process it.
var clean_agent_list = l_c_agent.join();
var add_url = 'test.php';
$.ajax({
url: add_url,
type: "GET",
data : { 'list_agent' : clean_agent_list },
success: function(data_return) {
//alert(data_return);
}
});
the output will be something like this (if using my example question above and we're check element with id 1,3 and 4 only)
1,3,4
if anybody have a better code, please write it here so that we can discuss which is better to solve my problem.
The method you want seems a bit backwards; the browser will already submit only the checked checkboxes, but here goes:
var re = /\[(\d+)\]$/,
numbers = [];
$('input[name^="a_r_id\\["]:checked').each(function() {
numbers.push(+this.name.match(re)[1]);
});
console.log(numbers.join(','));
It selects all checked boxes whose name starts with "a_r_id[". Then, a regular expression is used to extract the number portion between square brackets and added to the list of values.
I think you want to do something like this
<input type="checkbox" value="1" id="a_r_id_1" name="a_r_id[]">
<input type="checkbox" value="2" id="a_r_id_2" name="a_r_id[]">
<input type="checkbox" value="3" id="a_r_id_3" name="a_r_id[]">
<input type="checkbox" value="4" id="a_r_id_4" name="a_r_id[]">
Radio Buttons seems to be more applicable here rather than checkboxes try this:
<input type="radio" name="radiogroup" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="radio" name="radiogroup" value="2" id="a_r_id[2]" name="a_r_id[2]">
<input type="radio" name="radiogroup" value="3" id="a_r_id[3]" name="a_r_id[3]">
You can get the selected value using
$("input:radio[name=radiogroup]").click(function() {
var value = $(this).val();
//
do something with var
//
});