Adding checkbox values with different input names - javascript

I have the following code which adds together checkboxes when they are selected and produces a total at the bottom of the page. This function uses the following code:
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 68.50;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseFloat(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum.toFixed(2);
}
</script>
These checkboxes are within a form, and I need the form to send through to an email account. At the moment because all the checkboxes share the same input name 'choice' the PHP will only send the last checked box value.
I need to change the checkboxes input name code to name the different checkboxes 'choice1' 'choice2' 'choice3'. What would I have to change in the javascript to in order for the function to calculate all the checkboxes names 'choice1' 'choice2' 'choice3' etc rather than just adding together all checkboxes named'choice'? I have little Javascript and PHP knowledge so any help would be grateful. Thanks.

Rather than make the checkbox names unique, it would be better to append "[]" to their name. This will cause PHP to convert the values into an array, rather than just keep the last value.
So you would want a name of choice[] rather than choice.
You can also find some sample code in this answer.

The code below works ok (a self contained web page). The problem is how to get the array (group) of checkboxes when they're called different names. If you use jquery you could give them all the same class, then get hold of them by that class, but if you're using bare javascript then you can get the elements by Tag name ("input" in the case of the checkbox), and check each one has a name attribute that starts with "choice", inoring those that don't start with "choice", like buttons (also an input) or maybe other checkboxes with different names. It's a bit inefficient if the page is huge, unless you group the checkboxes some way.
To group them, you cold put them in a tag like
`<div id="checkboxes"> (checkboxes go here) </div>`
then use
`var cb = document.getElementById("checkboxes");`
`var arrInputs =cb.getElementsByTagName("input");`
for the line to get the arrInputs array. This would just get input type elements from within the Div. Hwever I dind't want to assume the page layout allows your checkboxes to be put in one div
Hope this helps
Doug
<script type="text/javascript">
function checkTotal() {
document.forms.listForm.total.value = '';
var sum = 68.50;
var frm=document.forms.listForm; // wasnt sure what your original listForm element was so I've put this form into a variable, frm
frm.total.value = '';
var arrInputs =document.getElementsByTagName("input"); // get all Input type elements on the form
for (i=0; i < arrInputs .length;i++) {
if (arrInputs[i].name.substr(0,6) == "choice") { // if the name starts with "choice"
if (arrInputs[i].checked) {
sum = sum + parseFloat(arrInputs[i].value);
}
}
}
frm.total.value = sum.toFixed(2);
}
</script>
</head>
<body>
<form name="listForm">
<a href='javascript:checkTotal()'>check</a><br>
<input type=checkbox name="choice1" value="1"><br>
<input type=checkbox name="choice2" value="2"><br>
<input type=checkbox name="choice3" value="3"><br>
<input type=checkbox name="choice4" value="4"><br>
<input type=checkbox name="choice5" value="5"><br>
<input type=checkbox name="choice6" value="6"><br>
<br>
<input type=text name=total value=""><br>
</form>
</body>
</html>

Related

Manipulating Text with JavaScript Based on Checkbox State

I'm trying to create a simple HTML page that presents a user with several options via checkboxes. I need to generate a string, stored in a variable that I can use on the page when a button is clicked, which will vary based on which boxes are checked.
The string will be a URL ("http://example.com/index.htm&term=") and will need to have additional text appended to it for each checkbox that is checked.
For example, if only a single box, say box1, is checked the string "box1" should be appended to the URL variable to look like "http://example.com/index.htm&term=box1"
If, however more than one box is checked, say box2 and box3 are checked, then the string "box2%20OR%20box3" should be appended to the URL string.
I'm pretty sure this can be done with JavaScript but I have no experience with it and would appreciate some guidance/examples.
Instead of storing it in a variable, I would recommend calling a function that builds the link when the button is pressed. If you really wanted to put it in a variable though, you would set up an event listener for the change event for each checkbox, and call the function to update the variable each time one of the checkboxes is checked or unchecked.
function checkboxUrl(checkboxes) {
const
url = `http://example.com/index.html`,
checkedArray = [];
for (let checkbox of checkboxes) {
if (checkbox.checked) checkedArray.push(checkbox);
};
const checkboxString = checkedArray.map(checkbox => checkbox.value).join(`%20OR%20`);
return url + (checkboxString ? `?term=` + checkboxString : ``);
}
let checkboxes = document.querySelectorAll(`input[type='checkbox']`);
label {
display: block;
}
<label><input type='checkbox' value='box1'>box1</label>
<label><input type='checkbox' value='box2'>box2</label>
<label><input type='checkbox' value='box3'>box3</label>
<button onclick='console.log(checkboxUrl(checkboxes))'>Get URL</button>
If you use Jquery you can do something like this:
<input type="checkbox" id="box1">
<input type="checkbox" id="box2">
<button type="button" id="myButton">Submit</button>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
var url = 'www.myurl.com/index.html&term=';
var checkboxList = [];
var params = '';
$(':checkbox:checked').each(function(){
checkboxList.push($(this).attr('id'));
});
params = checkboxList.join('%'); //will output "box1%box2"
url += params //www.myurl.com/index.html&term=box1%box2
window.location.href = url;
});
});
</script>

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)
}

Submitting a form using javascript?

I have a gender field in my form.
I have given it the same name, i.e. 'gender', and I have given it the same id, i.e. 'gender'.
Now I want to show what I have selected out of the two options. But with same id, it is not working. I have applied the onclick event to a textbox and I want it so whenever I click on that textbox, I show a javascript alert showing what I have selected, either male or female.
Please help!
gender:<input type="radio" name="gender" id="gender" value="female"/>female
:<input type="radio" name="gender" id="gender" value="male" />male
<input type="text" name="textbox" onclick="check()" />
<script type="text/javascript">
function check()
{
var a=document.getElementById("gender").value;
alert(a);
}
</script>
function addUser() {
//how to check what is the selected radio input
alert(getCheckedRadioId('u_type'));
}
function getCheckedRadioId(name) {
var elements = document.getElementsByName(name);
for (var i=0, len=elements.length; i<len; ++i)
if (elements[i].checked) return elements[i].value;
}
</script>
now this code alerts that what i have choosen but the problem is that i want the alert's value in a variable so that i could send this value to database...so how should i take the alerted value in a variable.....
You might wanna have a look at this:
javascript selected radio
Basically if you had a function that gets the checked radio value by name the problem would be solved. Adopted from the link above:
var selected = '';
var elements = document.getElementsByName('gender');
for (var i = 0, i < elements.length; i++)
{
if (elements[i].checked)
selected = elements[i].value;
}
alert(selected);
Also you might consider using jQuery. It would help a lot in cases like this one.
Your problem is that each element must have a unique Id, and you are giving two elements the same Id. I am not sure which one getElementById() would return. I assume the first.
However, you are quite ok giving multiple elements the same name. Then you could use getElementsByName() to retrieve an array containing the two elements, and you could return whether the element's Checked property is set.

how to call a javascript function on radio button's 'checked' property?

I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />

Use javascript comma separated variable to repopulate a forms checkbox values when page loads

I have a jquery variable that is storing a comma separated list of id names. I need help writing something in jquery that separates that variable and uses those values to populate a forms checkbox values when the page loads.
so my jquery variable is $storedFormValues that is a comma separated list of values "checkbox1, checkbox, etc."
and my form
<form name="formname" id="formid">
<input type='checkbox' class='catcheck' id='checkbox1' value='checkbox1' name='catselect' />Checkbox 1
<input type='checkbox' class='catcheck' id='checkbox2' value='checkbox2' name='catselect' />Checkbox 2
<input type="submit" name="submit" value="Submit" />
</form>
Any help would be greatly appreciated!
This should do it:
var $storedFormValues = "checkbox3,checkbox5";
$(function() {
$.each($storedFormValues.split(","), function(intIndex, objValue) {
$("#" + objValue).attr("checked", "true");
});
})
See the fiddle: http://jsfiddle.net/xNyww/
Not jQuery, but plain JS: You can use split to separate the values in an array:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
I do not know what do the csv looks like. If it's only one line, e.g:
checkbox1, checkbox7, checkbox2
then use it as:
var checkboxes[] = csvString.split(",");
for (str in checkboxes) {
$("#"+str).yourActionHere();
}
If it's several lines (one per checkbox) , e.g.
checkbox1, true
checkbox2, false
then :
var checkboxes[] = csvString.split(/\r\n|\r|\n/);
for (str in checkboxes) {
var data = str.split(",");
$("#"+data[0]).yourActionHere(data[1]);
}
Live Demo
var storedFormValues = "checkbox1, checkbox3, checkbox4";
$('#formid').children('input[id^=checkbox]').each(function() {
if (storedFormValues.indexOf($(this).attr('id')) != -1) {
$(this).attr('checked', 'checked');
}
});
Note: If you plan on having more than 10 checkboxes, I recommend naming them with a leading zero (ex: checkbox01) otherwise you may run into an issue where checkbox1 matches against checkbox11.

Categories