How to manipulate form field values in javascript - javascript

I'm trying to get the value of a few checkboxes and enter them in a hidden form field.
My checkboxes look like this:
<form>
<input type="checkbox" name="chicken" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="meat" id="meat" value="meat"/>Meat
</form>
<form method="post" action="">
<input type="hidden" name="my-item-name" value="" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I only need to submit the hidden field data so I'd like the value of the hidden field change when the checkbox is ticked. So if the first checkbox is ticked I'd like the value of the hidden field to become chicken and if both of them are ticked the value should be chicken,meat.
I'm using the following javascript
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++)
{
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}
but when I add the items, it adds both of them, it doesn't check which one's been checked, is there a way to fix that, so when the first item is checked it'll only add that item and if both of them are checked, it'll add 2 items separated by comma,

for(i = 0; i < checks.length; i++)
{
if (!checks[i].checked)
continue;
....
}

You need to give the checkboxes the same name to have them grouped:
<input type="checkbox" name="food[]" id="chicken" value="chicken"/>Chicken
<input type="checkbox" name="food[]" id="meat" value="meat"/>Meat
And in your JavaScript function:
function SetHiddenFieldValue() {
var checks = document.getElementsByName("food[]");
var hiddenFieldVal = "";
for (var i=0; i<checks.length; i++) {
if (checks[i].checked) {
if (hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}

You forgot to test for checks[i].checked
function SetHiddenFieldValue() {
var checks = document.getElementsByName("checkbox");
var hiddenFieldVal = "";
for(i = 0; i < checks.length; i++) {
if (checks[i].checked) {
if(hiddenFieldVal != "")
hiddenFieldVal += ",";
hiddenFieldVal += checks[i].value;
}
}
}
document.getElementById('my-item-name').value = hiddenFieldVal;
}

Hi your best to put the values into an array, makes it easier to then create the comma separated value. Also makes it a lot easier if you add more options later.
function SetHiddenFieldValue()
{
var checks = document.getElementsByName("checkbox");
var foods = new Array();
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
foods[i] = checks[i].value;
}
}
document.getElementById('my-item-name').value = foods.join(",");
}

Related

I want to get checkbox values

It always says if (checks[i].checked === true ) this is error I face...
I want to get value from checkbox Value...
function submitFun() {
var checks = document.getElementsByClassName('checks')
var str = "";
for (let i = 0; i < 3; i++) {
if (checks[i].checked === true) {
str += checks[i].value + "";
}
}
alert(str);
}
<div class="container">
<input type="checkbox" class="checks" value="뜨거워"> hot
<input type="checkbox" class="checks" value="추워"> clod
ok
</div>
you're iterating three ( 3 ) times when you have two ( 2 ) checkboxes, by the end of your loop, i will be 2 and check[2] is undefined, do i < checks.length instead of i < 3 :
function submitFun() {
var checks = document.getElementsByClassName('checks')
var str = "";
for (let i = 0; i < checks.length; i++) {
if (checks[i].checked === true) {
str += checks[i].value + " ";
}
}
alert(str);
}
<div class="container">
<input type="checkbox" class="checks" value="hot"> hot
<input type="checkbox" class="checks" value="cold"> clod
ok
</div>
Use querySelectorAll for selecting all check box also , also use checks.length in for loop to prevent null pointer on the array
See below working snippet
function submitFun() {
var checks = document.querySelectorAll('.checks')
var str = "";
for (let i = 0; i < checks.length; i++) {
if (checks[i].checked === true) {
str += checks[i].value + "";
}
}
alert(str);
}
<div class="container">
<input type="checkbox" class="checks" value="뜨거워"> hot
<input type="checkbox" class="checks" value="추워"> clod
ok
</div>
Try this.
Avoid attaching events in HTML (it is discouraged)
Use array.length while iterating, or better use Array.forEach()
function submitFun() {
var checks = document.getElementsByClassName('checks')
var str = "";
for (let i = 0; i < checks.length; i++ ){
if (checks[i].checked === true ) {
str += checks[i].value + "";
}
}
alert(str);
}
document.querySelector('a').addEventListener('click', () => {
submitFun();
});
<div class = "container">
<input type="checkbox" class ="checks" value ="뜨거워"> hot
<input type="checkbox" class ="checks" value ="추워"> clod
ok
</div>

code not executing after for loop -- javascript

I'm writing a function that is supposed to loop through all my checkboxes and load the "value" of the checkboxes that are checked into an array, however nothing is executing beyond the first for loop. I'm completely stumped here, what am I missing?
function saveSettings(){
var count = 1; //count for db
var checked=[]; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for(var i=0; i<=2; i++) { //loads checked array with checked values
if(document.getElementById("check"+i).checked == true){
checked[inc] = document.getElementById("check"+i).value;
alert(checked[inc]) // <------ executing as expected
inc++;
}
}
alert("made it") // <------ not executing
if(checked.length>0){ // loads checked values into dataString
for(var i=0; i == checked.length; i++){
if(i == 0){
dataString = "co_" + count +"="+checked[i]
}
else {
dataString = dataString +"&co_" + count +"="+checked[i]
}
count++;
}
}
alert(dataString)
From your description of the problem, I think the problem is the number of checkboxes, if you have only 2 checkboxes then the condition i<=2 will cause problem because docuement.getElementById('check2') will be undefined causing an error like Uncaught TypeError: Cannot read property 'checked' of null in your console.
Since you are trying to deal with dynamic number of elements try to use a class to select the checkboxs of interest like
function saveSettings() {
var checked = [];
var dataString = "x";
var checks = document.getElementsByClassName('check');
//if you can't add a class then fetch all the checkboxes in the page
//var checks = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked == true) {
checked.push(checks[i].value);
}
}
console.log("made it: ", checked)
if (checked.length > 0) {
dataString = '';
for (var i = 0; i < checked.length; i++) {
dataString += (i == 0 ? '' : '&') + "co_" + i + "=" + checked[i]
}
}
alert(dataString)
}
<input type="checkbox" class="check" id="check0" value="1" />
<input type="checkbox" class="check" id="check1" value="2" />
<input type="checkbox" class="check" id="check2" value="3" />
<br />
<button onclick="saveSettings()">Test</button>
in this line
if(document.getElementById("check"+i).checked == true){
//...
the getElementById will return an undefined value, and undefined does not have the .checked property.
how many checkboxes do you have in the document?
your second for loop had a mistake
function saveSettings(){
var count = 1; //count for db
var checked=[]; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for(var i=0; i<=2; i++) { //loads checked array with checked values
if(document.getElementById("check"+i).checked == true){
checked[inc] = document.getElementById("check"+i).value;
alert(checked[inc]) // <------ executing as expected
inc++;
}
}
alert("made it") // <------ not executing
if(checked.length>0){ // loads checked values into dataString
for(var i=0; i < checked.length; i++){
if(i === 0){
dataString = "co_" + count +"="+checked[i]
}
else {
dataString = dataString +"&co_" + count +"="+checked[i]
}
count++;
}
}
alert(dataString)
}
<input type="checkbox" id="check0"/>
<input type="checkbox" id="check1"/>
<input type="checkbox" id="check2"/>
<button onclick="saveSettings()">Run</button>
Try below working solution. Second for loop condition in your code (i == checked.length) is wrong. It should be i < checked.length)
function saveSettings() {
var count = 1; //count for db
var checked = []; //array of checked values
var inc = 0; //only incremented when checkbox is checked
var dataString = "x";
for (var i = 0; i <= 2; i++) { //loads checked array with checked values
if (document.getElementById("check" + i).checked == true) {
checked[inc] = document.getElementById("check" + i).value;
inc++;
}
}
if (checked.length > 0) { // loads checked values into dataString
for (var i = 0; i < checked.length; i++) {
if (i == 0) {
dataString = "co_" + count + "=" + checked[i]
}
else {
dataString = dataString + "&co_" + count + "=" + checked[i]
}
count++;
}
}
alert(dataString)
}

JavaScript Form Validation -

I'm trying to get a basic javascript validation. For some reason it's picking up text and drop downs but not radio buttons? What am I doing wrong?
JS Fiddle
<script>
function validateForm(formId)
{
var inputs, index;
var form=document.getElementById(formId);
inputs = form.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
if (inputs[index].value==null || inputs[index].value==""))
{
alert("Field is empty");
return false;
}
}
</script>
To validate for radio buttons, You need to go through all radio's and see which one's checked property is true.
<script>
function validateForm(){
for(i=0; i<document.form.radios.length; i++){
if(document.form.radios[i].checked==false){
c=1;
}
else{
c=0;
break;
}}
if(c==1){
alert('Please select an option');
}
}
</script>
document.form.radios.length gives the number of radio buttons.
You can also use HTML's required attribute to achieve the same functionality.
<form>
<input type="radio" name="gender" value="Male" required /> Male
<input type="radio" name="gender" value="Female" /> Female
<input type="submit" name = "sub" value="SAVE" />
</form>
Fiddle
Provided below is an approach you can take to identify if you have multiple radio buttons in your form
function hasEmptyRadio(radioMap) {
var emptyRadio = false;
for (var i in radioMap) {
if (radioMap.hasOwnProperty(i) && !radioMap[i]) {
emptyRadio = true;
break;
}
}
return emptyRadio; // return the radio object or name if required
}
function markEmptyRadios(radioMap, radioObj) {
var checked = radioObj.checked;
radioMap[radioObj.name] = radioMap[radioObj.name] || checked;
}
function validateForm(formId) {
var inputs, index;
var radioMap = {};
var form = document.getElementById(formId);
inputs = form.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
if (inputs[index].type === 'radio') {
markEmptyRadios(radioMap, inputs[index])
}
// Your check for other input type can go here
}
alert("Radio Empty check returned => " + hasEmptyRadio(radioMap));
}

how to check checkboxes in javascript

I have three checkboxes in html.
In Javascript I have variable newspaper = "jang,News,Dawn";
Now I want to check the checkboxes based on newspaper values if it contain only jang then only jang check box should be checked if it contain jang,News,Dawn then all three checkbox should be checked.
The code I have written always checked last two checkboxes which is wrong.
My code is:
var newspaper = document.forms[0].newspaper;
var a = "Jang,News";
var news = ["Jang", "Dawn", "News"]
for (i = 0; i < news.length; i++)
{
if (a.indexOf(news[i]))
{
newspaper[i].checked = true;
}
}
<input type="checkbox" name="newspaper[]" value="Jang">Jang<br />
<input type="checkbox" name="newspaper[]" value="Dawn">Dawn<br />
<input type="checkbox" name="newspaper[]" value="News">The News
If you want to do it using Javascript only, you have to do some changes in your code :
Change the name of all the checkboxes to "newspaper" (without square brackets)
<input type="checkbox" name="newspaper" value="Jang"/>Jang<br />
<input type="checkbox" name="newspaper" value="Dawn"/>Dawn<br />
<input type="checkbox" name="newspaper" value="News"/>The News
Check indexOf return value is not equal to -1 :
if (a.indexOf(news[i]) != -1) {
newspaper[i].checked = true;
}
Here is the working demo.
var newspaper = document.forms[0]["newspaper[]"];
var a = "Jang,News";
for (i = 0; i < newspaper.length; i++)
{
if(a.indexOf(newspaper[i].value) > -1){
newspaper[i].checked = true;
}
}
Yeah, I would review your code, and the names of your elements. But here, this works.
http://jsfiddle.net/3qeeox0a/
Try this-
var newspaper = document.forms[0].newspaper;
var a = "Jang,News";
var news = ["Jang","Dawn", "News"]
for (i = 0; i < news.length; i++)
{
if (a.indexOf(news[i]) != 1)
{
newspaper[i].checked = true;
}
}
Fiddle:-http://jsfiddle.net/um0y5wrp/9/
Please change the code, and replace this:
if (a.indexOf(news[i]))
{newspaper[i].checked = true;
}
by:
for(j = 0; j < newspaper.length; j++){
if(newspaper[j].value == newspaper[i].value){
if (a.indexOf(news[i])){
newspaper[j].checked = true;
}
}
}

Javascript: Detect checked boxes isn't working with form with only 1 checkbox. Working with 2 or more

I have the function below. It gets the values from checked boxes and transfer it to a textbox. It is working... but only if the form has 2 or more checkboxes.
<script type="text/javascript">
function sendValue()
{
var all_values = '';
boxes = document.DataRequest.itens.length
for (i = 0; i < boxes; i++)
{
if (document.DataRequest.itens[i].checked)
{
all_values = all_values + document.DataRequest.itens[i].value + ","
}
}
window.opener.document.getElementById('emailto').value = all_values;
self.close();
}
</script>
<form name="DataRequest">
<input name="itens" type="checkbox" value="name1">
<input name="itens" type="checkbox" value="name2">
</form>
Am I missing something to make this work with only 1 checkbox?
When there is one item. it does not return array
function sendValue()
{
var all_values = '';
boxes = document.DataRequest.itens.length
if(boxes>1)
{
for (i = 0; i < boxes; i++)
{
if (document.DataRequest.itens[i].checked)
{
all_values = all_values + document.DataRequest.itens[i].value + ","
}
}
}
else
{
if (document.DataRequest.itens.checked)
{
all_values = document.DataRequest.itens.value
}
}
window.opener.document.getElementById('emailto').value = all_values;
self.close();
}
First, you need to give different names to your inputs :
<form name="DataRequest">
<input name="item1" type="checkbox" value="name1">
<input name="item2" type="checkbox" value="name2">
</form>
Using the same name to your inputs is technically possible in your case but a terrible practice as the name is normally what's identify for a form the different inputs.
Then, to access your inputs, you must use a different syntax. More than one version are possible but you can do this :
var boxes = document.forms['DataRequest'].getElementsByTagName('input');
var tokens = [];
for (var i=0; i<boxes.length; i++) {
if (boxes[i].checked) tokens.push(boxes[i].name+'='+boxes[i].value);
}
var all_values = tokens.join(',');
Note that the use of join avoids the trailing comma.
not sure how much compatibility you need with IE 6 - 8, but if that's not required you can use
function serializeChecked() {
var values = [];
var checked_boxes = document.querySelectorAll('form[name="DataRequest"] input[checked]');
for (var i = 0, l = checked_boxes.length; i < l; i++) {
values.push(checked_boxes[i].getAtrribute('value'))
}
return values.join(',');
}
function sendValue() {
window.opener.document.getElementById('emailto').value = serializeChecked();
}
If you do require IE support, use document.DataRequest.getElementsByTagName('input') instead of QSA and iterate through them to collect the values if they have the checked attribute.

Categories