JavaScript for loop "document.getElementById" - javascript

Hi I am trying to go throw radio buttons using a for loop , with ID of "Group" and get the value of it show out here is my code but it doesnt alert the value of them on submit,
http://jsfiddle.net/JAwZg/

HTML:
<input type="radio" id="group1" name="group" value="1" />
No Changes<br/>
<input type="radio" id="group2" name="group" value="2" />
Gray Scale <br/>
<input type="radio" id="group3" name="group" value="3" />
Old Style<br/>
<input type="radio" id="group4" name="group" value="4" />
Sharpening<br/>
Script:
var ims = document.getElementsByName("group");
for(var i = 0; i < ims.length; i++){
ims[i].onclick = function(){alert("hi");}
}
​http://jsfiddle.net/JAwZg/4/

you can also do that like this.instead of ID give it a class
var yourString;
$.each($('.className'), function(i, k){
yourString += $(k).val()+',';
});
yourString = $.trim(yourString);
yourString = yourString.substring(0, yourString.length - 1);

Related

Changing URL on radio button selection

I'm trying to change the URL when I select radio button.
I have found an answer that works for 'select' form elements, but if I apply it to my radio buttons it lists out all the options instead of the one that is selected
My JS
$('.unitfiltercontrol').change(function(){
var params =[];
$('.unitfiltercontrol').each(function(){
$this=$(this);
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
});
$('#urlDisplay').text(window.location.href+('?'+params.join('&'))); //print to div for testing
});
My HTML:
<form>
<input id="radio1" type="radio" value="1" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio2" type="radio" value="2" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio3" type="radio" value="1" name="bar" data-param="bar" class="unitfiltercontrol">
<input id="radio4" type="radio" value="2" name="bar" data-param="bar" class="unitfiltercontrol">
</form>
<div id="urlDisplay"></div>
So if I select radio1, instead of the URL being displayed as:
/?foo=1
I get:
/?foo=1&foo=2&bar=1&bar=2
How would I modify this to work with radio buttons?
Hi friend you can use if condition when pushing parameters to like below
$('.unitfiltercontrol').change(function(){
var params =[];
$('.unitfiltercontrol').each(function(){
$this=$(this);
if ($(this).prop("checked")) { //get the values of only checked radio buttons
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
}
});
$('#urlDisplay').text(window.location.href+('?'+params.join('&'))); //print to div for testing
});
Radio button in your case make single selection , so no need to loop each radio , just get in the change the value and data for current clicked , then create object using data-param as key , after that loop thorough keys and create and array of key + values as below ; snippet :
let values = {};
$('.unitfiltercontrol').change(function(e){
let data = $(this).data('param');
let value = this.value;
values[data] = value;
let params = [];
let keys = Object.keys(values);
for(inc = 0; inc < keys.length ; inc ++) {
let key = keys[inc];
params.push(key+'='+encodeURIComponent(values[key]))
}
$('#urlDisplay').text(window.location.href+('?'+params.join('&')));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My HTML:
<form>
<input id="radio1" type="radio" value="1" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio2" type="radio" value="2" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio3" type="radio" value="1" name="bar" data-param="bar" class="unitfiltercontrol">
<input id="radio4" type="radio" value="2" name="bar" data-param="bar" class="unitfiltercontrol">
</form>
<div id="urlDisplay"></div>
<div id="urlDisplay">
</div>

jQuery, collecting checkboxes and put selected ones to array, is that possible?

I want to collect checked checkboxes (values) with a classname and put them into an array. Just like that one:
var a = new Array();
$('.categoriesCb').each(function(i, item) {
if ($(item).prop('checked'))
{
a.push($(item).val());
}
alert(JSON.stringify(a));
});
my problem is its a bit big. Cant it be done with one-line?11
You can use .map() function along with .get(). You can also eliminate paramete item and use context this:
var a = $('.categoriesCb:checked').map(function(){
return $(this).val();
}).get();
Use jQuery.map()
$('.categoriesCb:checked').map(function() {
return this.value;
}).get();
another way is to use jQuery.makeArray() with .map():
var arr = jQuery.makeArray($(':checked').map(function(){ return this.value; }));
$('pre').html(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />
<br>
<pre></pre>
Just a pure JS single liner. Note that node list to array conversion with the spread operator works fine in Firefox but with Chrome it's only possible with v51 on. Otherwise you will have to go with the good old Array.prototype.map.call(document.querySelectorAll("input[type=checkbox][checked]"), e => e.value) method.
var arr = [...document.querySelectorAll("input[type=checkbox][checked]")].map(e => e.value);
console.log(JSON.stringify(arr));
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />

jQuery & JavaScript Excercise: Adding Values On Condition

How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO

Javascript: Image not matching value of radio button

I am working with radio buttons and displaying an image depending on the radio button chosen. But somehow I am receiving an error with the image array. I only get two pictures displayed and does not match the proper value. Is the error in my array or the html? EXAMPLE
Reference of bikes:
Bike1.jpg
Bike2.jpg
Bike3.jpg
JS
<script>
function check_value(val) {
var imgs = ['images/bike1.jpg', 'images/bike2.jpg', 'images/bike3.jpg'];
var img = imgs[val];
var el = document.getElementById("imgBox");
if (img) {
el.src = img;
el.style.display = "";
}
}
</script>
HTML
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(1)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(2)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(3)'/> Aprilia RSV4<br />
</form>
<img id="imgBox" src="#" style="display:none">
Arrays are zero-indexed. You should call:
check_value(0)
to get the first item, and 1 for the second, 2 for the third.
Note how choosing your first item loads the second image, and the second item the third.
Arrays start at index 0, so you have the following alternatives:
use imgs[val-1]
change your array to [null, "img1", "img2 ...]
start your images at img0
However, a much better approach is:
function check_value(val) {
var el = document.getElementById("imgBox");
if (val>0 && val<4) { //will trigger when [1,2,3], modify it according to your needs
el.src = "images/bike" + val + ".jpg";
el.style.display = "";
}
}
Javascript arrays are indexed starting from 0 and going up. So
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(1)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(2)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(3)'/> Aprilia RSV4<br />
</form>
Should be
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2)'/> Aprilia RSV4<br />
</form>

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

Categories

Resources