Get proper checkbox value using form.serialize - javascript

We are currently using $('form').serialize() to get all form information
This will return any checkbox values as "On" or "Off".
Is there any way to get a 1/0 or true/false value using this same method?

Yes. You can do it by adding a hidden input with the same name as checkbox which value will be submitted if checkbox is unchecked:
<input type="hidden" name="option" value="false"/>
<input type="checkbox" name="option" value="true"/>
It will submit both values if checkbox is checked. But server side will read the latest one (value of checkbox)

The value of a form control is always a string. You can use radio buttons to get different values for the same control name:
<form ...>
<input type="radio" name="whatever" value="true">true
<br>
<input type="radio" name="whatever" value="false">false
...
</form>
Only one can be checked, and only the checked name/value will be sent to the server.

If we have multiple checkboxed in our page like :
<input id="reminder" name="Check1" value="false" type="checkbox" />
<input id="alarm" name="Check2" value="false" type="checkbox" />
we have to bind the change event of these checkboxes and set its value to true or false.
$('input[type=checkbox]').on('change', function(){
var name = $(this).attr('name');
if($(this).is(':checked')){
$('input[name= "' +name +'"]').val(true);
$(this).val(true);
}
else{
$(this).val(false);
$('input[name= "' +name +'"]').val(false);
}
});
By default, checkbox value doesn't appear in $('form').serializeArray(), It appears when it is checked.
We have to keep one hidden field for each checkbox like :
<input type="hidden" value="false" name="Check1" />
<input type="hidden" value="false" name="Check2" />
Now when we serialize the form now, we get the correct value like :
Check1=true
Check2=false

<input type="checkbox" name="check1" value="true" id="check1">
just set the value

You can add a new class for check boxes and set value when clicked.
<input class="checkbox" id="someId" type="checkbox" value="false" />Checkbox
And use a small JQuery helper
$('.checkbox').click(function () {
$(this).val() == "false" ? $(this).val("true") : $(this).val("false");
});
Then you will be able to get the value of the check box or serialize a form.

Related

select checkbox by name and check if it checked javascript

I am trying to test if checkbox is checked.
I have more inputs and they have different names.
I managed to select the input but I can't seem to check if it wa selected. If I add to the condition '= true' it is checked once I load the page. If I leave it just .checked it doesn't do anything
Have I selected the input right? Please note I want to select it by name rather than id or class
Why is it that once the page loads my condition for if statement doesn't work?
<input type="checkbox" name="name1">
<input type="checkbox" name="name2">
<input type="checkbox" name="name3">
<input type="checkbox" name="name4">
const firstInput = document.getElementsByName('name1');
if (firstInput[0].checked) {
console.log('checked');
}
You are selecting element with name "1" but don`t have element with such name.
If you want to select all inputs which name attribute starts with "name":
const firstInput = document.querySelectorAll('[name^=name]')
You need to add attribute to that input. Attach an onclick listener and invoke
getAttribute
setAttribute
to manipulate 'checked' attribute;
<input type="checkbox" onclick="myFunction()" name="name1">
<input type="checkbox" onclick="myFunction()" name="name2">
<input type="checkbox" onclick="myFunction()" name="name3">
<input type="checkbox" onclick="myFunction()" name="name4">
function myFunction() {
var $element = document.getElementsByName('name1')[0];
var checked = $element.getAttribute('checked') === 'true';
$element.setAttribute('checked', !checked);
console.log($element.getAttribute('checked'));
}

Cannot deselect radio button?

I have been attempting to allow radio buttons to be deselected using jQuery, but I am running into issues with the prop function. When this code runs, my conditional ($(e.currentTarget).prop('checked')) always evaluates to true.
Here is a fiddle which demonstrates my issue: Jsfiddle
FYI: I am using jQuery 1.8.2, and I cannot update it because it is a legacy project with many dependencies. Also, I MUST use radio buttons per the client's request.
Javascript:
$("input[name=optionMedia]").click(function(e) {
if ($(e.currentTarget).prop('checked')) {
$(e.currentTarget).prop('checked', false);
}
});
Html:
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
You can do it like this
$('input.bigSizeInput').mouseup(function() {
if ($(this).is(':checked')) {
setTimeout(function() {
$('input.bigSizeInput:checked').prop('checked', false);
}, 1)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1" />
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />
This is because checked is a property. If its there it is true, if its not it is not true. Hence you either should switch to a checkbox or use
$("..").removeProp('checked')
Using checkbox to check/uncheck is better than radio button. But if you want to use radio button, you need to check if radio is checked, copy it using and remove checked attribute of copied element and then insert it after target radio. At the end remove original radio.
$(document).on("mousedown", "input[name=optionMedia]", function(e) {
if (this.checked)
$(this).clone().prop('checked', false).insertAfter(this).end().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

How to set a default radio button with a value?

General issue: I cannot set a default radio button in my radio groups unless I remove the value attribute from the inputs.
Specifics: Each input has a value that is needed as it is being used by angular in other places in the app. So, I need to know how to set an input to default checked while retaining the values on the inputs. It has the same behavior if I try to add checked with jQuery instead of in HTML.
I have looked at several related questions including here. The specific issue is I need to have values and be able to set one input to checked as a default. The first input is set to checked, but it does not actually work unless I remove the value from that input.
Here is the HTML:
<div class="radio">
<label>
<input type="radio" ng-model="optionsRadios" id="new" value="new" checked>
New
</label>
<label>
<input type="radio" ng-model="optionsRadios" id="used" value="used">
Used
</label>
<label >
<input type="radio" ng-model="optionsRadios" id="broken" value="broken">
Broken
</label>
</div>
You have to use ng-checked="true" instead of checked
<input type="radio" ng-model="optionsRadios" id="new" value="new" ng-checked="true">
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">
<p>My cars:</p>
<input type="radio" ng-model="all" value="Volvo" ng-checked="true">Volvo<br>
<input type="radio" ng-model="all" value="Ford">Ford<br>
<input type="radio" ng-model="all" value="Mercedes">Mercedes
</body>
</html>
If you have a group of radio button and you want to set radio button checked based on model, then radio button which has same
value and ng-model is checked automatically.
<input type="radio"
ng-model="optionsRadio" value="1" >
<input type="radio"
ng-model="optionsRadio" value="2" >
<input type="radio"
ng-model="optionsRadio" value="3" >
If the value of optionsRadio is "2" then second radio button will be selected automatically.
In Your Case:
When u r initiating the controller all u have to do is to assign a value to your model to keep atleast one radio button selected.
Controller part:
$scope.optionsRadio = "new";
Form part:
<input type="radio" ng-model="optionsRadio" value="new" >
<input type="radio" ng-model="optionsRadio" value="used" >
<input type="radio" ng-model="optionsRadio" value="broken" >
First radio button will be selected automatically.
Note:
If value doesn't work u can use ng-value.

Creating an Associative Array using JQuery

I am trying to create an associative array using JQuery. I would like it to be filled with the values of the checkboxes a user has selected from the UI.
I was creating the array like this at first:
$contentArray = [];
$('.content-filter :checked').each(function(){
$contentArray.push(this.value);
})
but the problem with this is that when I pass it to a php script via Ajax it was making it very difficult to get values from it. I'd rather be able to get the values from the array based on the key associated with it.
So I decided to modify my code to this:
$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter :checked').each(function(){
$contentArray[this.value] = this.value;
})
however now when I perform console.log I am being told the contents of my array contains nothing.
Can anyone advise me on how to fix this issue and show me where I am going wrong?
Your filter is wrong - you need to remove the space before :checked, otherwise it will look for an element inside the checkbox which is checked, which obviously doesn't exist:
$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
$contentArray[this.value] = this.value;
})
console.log($contentArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />
However, as mentioned, this just creates a fragmented array. If you want truly associative keys, you should create an object (tho I don't see this being easier to process in php):
$contentObject = {}; //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
$contentObject[this.value] = this.value;
})
console.log($contentObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />

What value passes from a form with checkbox to the java script

I take a form and wants value of checkbox.
such as:
<form method="post" onSubmit="return nameempty()">
<input name="checkn1" id="check1" type="checkbox" />
<input name="checkn2" id="check2" type="checkbox" />
<input type="submit" value="submit">
</form>
Now I want to know the values of checkbox when it is selected, and also when not selected.
Now I write javascript, and get that each checkbox has value "on" whether it is selected or not.
<script>
function nameempty()
{
alert(document.getElementById('check1').value);
alert(document.getElementById('check2').value);
}
</script>
How could I get 'on' when it is selected and anything else when not selected.
use checked instead of value which will return true if the checkbox is checked or it will return false
<script>
function nameempty()
{
alert(document.getElementById('check1').checked);
alert(document.getElementById('check2').checked);
}
</script>
One way to get the value of a 'checked' check box which includes the check if 'checked'
var check1value = document.querySelector('#check1:checked').value;
In the html you are missing a value attribute (if checked)
<input name="checkn1" id="check1" value="value-here" type="checkbox" />

Categories