Explode checkbox input value in javascript - javascript

So i have input checkbox code like this:
<input type='checkbox' name='cek[]' class='check1' value='$data[id_usulan]' >
And there is an input text with id = test2, so when i click the checkbox, the input text value will change to checkbox value (there's no problem with this), i use this javascript code to do it:
$("input[type=checkbox]").click(function(){
var sum=0;
if ($("input[type=checkbox]").is(':checked')) {
$("input[type=checkbox]:checked").each(function(index){
sum += Number($(this).val().replace( /[^\d.]/g,''));
});
}
$("#test2").val(sum);
} );
And then i change the checkbox:
<input type='checkbox' name='cek[]' class='check1' value='$data[id_usulan]/$data[jml_harga]' >
As you can see, i tried to use 2 value in one checkbox ($data[id_usulan] and $data[jml_harga], separated by '/' ), but i just want to use one value ($data[jml_harga]) for $(this).val(), well you might think that if i want to use $data[jml_harga] then i don't have to make 2 value, but don't ask that, there's another reason for why i use 2 value.
So this is what I have tried:
$("input[type=checkbox]").click(function(){
var sum=0;
if ($("input[type=checkbox]").is(':checked')) {
$("input[type=checkbox]:checked").each(function(index){
var explode = $(this).val().split('/');
var price = explode[2];
sum += Number(price.replace( /[^\d.]/g,''));
});
}
$("#test2").val(sum);
} );
But when i click the checkbox, the input text value didn't change to checkbox value and remains the same as before I check, so how to fix this problem?
If anyone has a way to solve this, please help me.. :)

Here is the problem:
var price = explode[2];
The second value is:
var price = explode[1];

Related

The radio inputs from my html are not interacting well with my if statements in javascript [duplicate]

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
var value = $('input:radio[name="radiogroupname"]:checked').val();

Getting value of multiple text inputs by class name and only returning value from the one that has value

I have multiple text inputs that all share the same class name.
Assuming the code has been written so that only one of those text inputs can have value at any one time, is it possible to search for the value of those text inputs by class name and only return the value of the one that has data written in it by the user?
For the purpose of this question, how would I get that value to be returned in the alert box in the code below?
var input = document.getElementsByClassName("input").value;
alert("input");
If it isn't possible using class names, is there an alternative solution that would achieve the same effect?
I would rather avoid having to give each text input an id and write code for each one, hence wanting to use class names.
//find all the elements, filter out the ones without a value, get the value
$('.theClass').filter(function(){ return this.value.trim(); }).val()
var $inputs = $('.aClass');
$inputs.on('input', function(){
$inputs.not(this).prop('disabled', this.value.trim());
});
$('button').on('click', function(){
console.log(
$inputs.filter(function(){ return this.value.trim(); }).val()
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input type="text" class="aClass"></div>
<div><input type="text" class="aClass"></div>
<div><input type="text" class="aClass"></div>
<div><input type="text" class="aClass"></div>
<div><button>Get Value</button></div>
Please try this below code,
var matches = document.getElementsByClassName('input');
for (var i=0; i<matches.length; i++) {
//do action
console.log(matches[i].value)
}

How to add sum in my input value and chage

I have this code:
<input id=​"InvoiceItemPrice:​:​:​:​" name=​"InvoiceItemPrice:​:​:​:​" value size=​"6">​
<input id=​"InvoiceItemPrice:​:​1:​:​" name=​"InvoiceItemPrice:​:​1:​:​" value=​"46.00" size=​"6">​
<input id=​"InvoiceItemPrice:​:​2:​:​" name=​"InvoiceItemPrice:​:​2:​:​" value=​"79.00" size=​"6">​,
<input id=​"InvoiceItemPrice:​:​3:​:​" name=​"InvoiceItemPrice:​:​3:​:​" value=​"14.00" size=​"6">​
I like add sum in every value ot input type i have this code:
var sum = 100/123;
$('input[name="InvoiceItemPrice::2::"]').each(function()
{
sum *= parseFloat($(this).val());
});
$('input[name="InvoiceItemPrice::2::"]').val(sum);
How to change all value on all input.
I tried with this $("input [name = ' * InvoiceItemPrice ']") but I caught the first that does not have a value and NaN gives me an error.
What is happening is your sum variable is getting re-used in your each statement, if you change that line inside of your each you should be A-ok.
I have created a jsFiddle here https://jsfiddle.net/r79d3121/3/ which may help
HTML
<input id="InvoiceItemPrice::::" name="InvoiceItemPrice::::" value size="6">
<input id="InvoiceItemPrice::1::" name="InvoiceItemPrice::1::" value="46.00" size="6">
<input id="InvoiceItemPrice::2::" name="InvoiceItemPrice::2::" value="79.00" size="6">,
<input id="InvoiceItemPrice::3::" name="InvoiceItemPrice::3::" value="14.00" size="6">
jQuery
var sum = parseFloat(100 / 123);
$(function () {
var result = 0;
$('[id*="InvoiceItemPrice"]').each(function () {
$(this).val(parseFloat((parseFloat($(this).val()) * parseFloat(sum))));
});
});
Updated to change only the value from the input selected
2nd Update, values are calculated when the document is ready, if you want the values to be updated you could always check for .focusout() on each input and then run the code to calculate the value
3rd Update, the html is back to the original and also, you can just user a partial selector in your jQuery which I have provided and updated the jsFiddle link
Try something like this:
$('input[name^=InvoiceItemPrice]').each(function() {
$(this).val("example");
});

How to get the selected radio button’s value?

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
var value = $('input:radio[name="radiogroupname"]:checked').val();

Is it possible to collect data on checked or unchecked tick boxes in HTML?

I'm looking at creating a very simple HTML page that contains an HTML form with a series of check boxes and input fields. The page would be roughly like so:
Input Forename ==== Input Surname ==== Input ID =====
Text checkbox1 value1 Text
Text checkbox2 value2 Text
Text checkbox3 value3 Text
Text checkbox4 value4 Text
Output Text value
Output Text value
Output Text value
Output Text value
Depending on which values are ticked (i.e. value 1/2/3/4), the value next to it is then calculated (for arguments sake let's say it's multiplied by 2) and then output below (where it says "Output text" value). Apologies if this doesn't match the "question" but you see what I mean by "collecting" data (i.e. the value next to the checkbox).
My question is thus, is it possible to use JavaScript to say, if tickbox1 is checked, please use "value1"? Once this is all completed the page just needs to have a "print" button (which is fine). There is no back end stuff that needs to happen and no data capture.
Hope this makes sense and thanks in advance
EDIT:Of course if it's a lot easier to do this with something like JQuery I'd be happy to explore this!
This code should help you out!
Questions[] is an array with all the input fields in,
getElementsByName goes through all the elements that have the same name (radio boxs for example all have the same name) and then finds out which one is checked, and then uses that value.
Answers[] is the array with the stored values in.
for (var i = 0; i < questions.length; i++) {
//Does the question name have more than one instance? (That would make it a checkbox or radio button...
if (document.getElementsByName(questions[i]).length > 1) {
//Lets loop through all these values and find out which one is selected, and then grab the value from it.
var x = document.getElementsByName(questions[i])
for(var k=0;k<x.length;k++)
if(x[k].checked){ //This is where it loops to find the checked answer
answers[i] = x[k].value;
//alert("radio saved " + answers[i]);
}
}
//Nope, only once, so its a text field or similar
else {
answers[i] = document.getElementById("answer" + questions[i]).value;
//alert("text saved " + answers[i]);
}
}
Hope this helps!
So to use this in your calculations (to say make it double) you could call
var answertoyourquestion = answers[i] + answers[i];
Well, you could try something like this(not tested):
var total = 0;
for (int i = 0;i < 10;i++)
{
var checkbox = document.getElementById("checkbox" + String.ValueOf(i));
if (checkbox.checked)
{
var valuebox = document.getElementById("value" + String.ValueOf(i));
total += (valuebox.value * 2);
}
}

Categories