How can we preserve the value of the input box whose corresponding checkbox is checked, and if the corresponding checkbox is not checked then clear input value from form?
<form onsubmit="finalSubmission">
<input type="checkbox" id="yourBox1" />
<input type="text" id="yourText1" />
<br>
<hr>
<input type="checkbox" id="yourBox2" />
<input type="text" id="yourText2" />
<br>
<hr>
<input type="checkbox" id="yourBox3" />
<input type="text" id="yourText3" />
<br>
<hr>
<input type="checkbox" id="yourBox4" />
<input type="text" id="yourText4" />
<br>
<hr>
<button type="submit">Submit</button>
</form>
I know I can do this way, but is there any other alternative approach for this. This is quite a length approach
function finalSubmission(event){
event.preventDefault();
let firstInputField;
let checkBox1 = document.getElementById("yourBox1");
if (checkBox1.checked == true){
firstInputField = true
} else {
firstInputField = false
}
if(!firstInputField){
document.getElementById('yourText').value = "";
}
}
Try this -
function finalSubmission() {
for (var i = 0; i < 4; i++) {
!document.getElementById("yourBox" + i).checked ? document.getElementById("yourText" + i).value = "" : null;
}
}
<input type="checkbox" id="yourBox1" />
<input type="text" id="yourText1" />
<br>
<hr>
<input type="checkbox" id="yourBox2" />
<input type="text" id="yourText2" />
<br>
<hr>
<input type="checkbox" id="yourBox3" />
<input type="text" id="yourText3" />
<br>
<hr>
<input type="checkbox" id="yourBox4" />
<input type="text" id="yourText4" />
<br>
<hr>
<button type="submit" onclick="finalSubmission">Submit</button>
Related
I have three fields that will be filled by the user.
one for the question, and the two others for the proposed answers. I want to give the user the possibility to add the third or as much as he wants propositions whenever he clicks at add proposition. I started coding the function but it's still missed
<head>
<script>
function myFunction(){
var x = document.createElement("LABEL");
var t = document.createTextNode("Titre");
x.appendChild(t);
}
</script>
</head>
<body>
<form id="myForm" method="POST" action="./exam_coordinates">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="checkbox" name="ans1" id="ans1" values="" />
<input type="text" name="ans1" id="ans1" value=""><br>
<input type="checkbox" name="ans2" id="ans2" />
<input type="text" name="ans2" id="ans2" value=""><br>
<br>
<button onclick="myFunction()">Add proposition</button> <br><br><br>
<input type="submit" value="submit">
</form>
</body>
If I'm getting your question right, you need to add inputs to get more answers from user as he wants. If so, see the following -
var addButton = $('#add_button');
var wrapper = $('#more_answers');
$(addButton).click(function(e) {
e.preventDefault();
var lastID = $("#myForm input[type=text]:last").attr("id");
var nextId = parseInt(lastID.replace( /^\D+/g, '')) + 1;
$(wrapper).append(`<div><input type="checkbox" name="ans${nextId}" id="ans${nextId}" values="" /> <input type="text" name="ans${nextId}" id="ans${nextId}" value=""/>Delete<div>`);
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form id="myForm" method="POST" action="./exam_coordinates">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="checkbox" name="ans1" id="ans1" values="" />
<input type="text" name="ans1" id="ans1" value=""><br>
<input type="checkbox" name="ans2" id="ans2" />
<input type="text" name="ans2" id="ans2" value=""><br>
<div id="more_answers"></div>
<br>
<button id="add_button">Add proposition</button> <br><br><br>
<input type="submit" value="submit">
</form>
</body>
In your function, you have to append your label as well in its parent. Like below -
function myFunction() {
var form = document.getElementById("myForm");
var input = document.createElement("input");
form.appendChild(input)
}
<form id="myForm" method="POST" action="./exam_coordinates">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="checkbox" name="ans1" id="ans1" values="" />
<input type="text" name="ans1" id="ans1" value=""><br>
<input type="checkbox" name="ans2" id="ans2" />
<input type="text" name="ans2" id="ans2" value=""><br>
<br>
<button type="button" onclick="myFunction()">Add proposition</button> <br><br>
<input type="submit" value="submit">
</form>
If you want to put your elements at any specific place, you should create a wrapper in your form element just like below -
function myFunction() {
let wrapper = document.getElementById("dynamic-fields");
var input = document.createElement("input");
wrapper.appendChild(input)
}
<form>
<!-- ...input fields... -->
<div id="dynamic-fields"></div> <br>
<!-- ...buttons.... -->
<button type="button" onclick="myFunction()">Add proposition</button>
</form>
This way it will put those dynamically generated elements on specific place in your form page.
Try this - https://jsitor.com/IO08f-WBx
HTML
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" /><label for="cat_1">cat_1</label><br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" /><label for="cat_2">cat_2</label><br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" /><label for="cat_3">cat_3</label><br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" /><label for="cat_4">cat_4</label><br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" /><label for="cat_5">cat_5</label><br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" /><label for="cat_6">cat_6</label><br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" /><label for="cat_7">cat_7</label><br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" /><label for="cat_8">cat_8</label><br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" /><label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Javascript
function calcAndShowTotal(){
var total = 0;
$('#catlist :checkbox[checked]').each(function(){
total =+ parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#pricelist :checkbox').click(function(){
calcAndShowTotal();
});
calcAndShowTotal();
I am getting particular value. WHY? I tried sum of total, i tried jquery but no success..
Use $('#catlist :checkbox:checked') selector to select checked check-boxes
[] is used as attribute selector and it could be used as '[type="checkbox"]' but it will not filter checked check-boxes
+ operator is not needed before parseFloat, it has to be total =+
Instead of calling handler, just invoke change handler using .change()
function calcAndShowTotal() {
var total = 0;
$('#catlist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Using Array#reduce
function calcAndShowTotal() {
var total = [].reduce.call($('#catlist :checkbox:checked'), function(a, b) {
return a + +$(b).attr('price') || 0;
}, 0);
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Instead of looping you can use change which will respond to and change event on the checkbox. Also you need add or subtract value like this += for addition on -= for subtraction
var _total = 0;
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')){
_total += parseFloat($(this).attr('price')) || 0;
}
else{
_total -= parseFloat($(this).attr('price')) || 0;
}
$('#total').val(_total);
})
JSFIDDLE
$('input:checkbox').change(function(){
var totalprice=0;
$('input:checkbox:checked').each(function(){
totalprice+= parseFloat($(this).attr('price'));
});
$('#total').val(totalprice)
});
I want chkbox1 to call a javascript function for txtbox1, chkbox2 to call the same function but for txtbox2, and so on.
To take it a step further, I want all checkboxes checked in their default state and I want the functions to run when unchecked.
How can I achieve this?
I only know simple way for one checkbox:
function OnChangeCheckbox(checkbox) {
if (checkbox.checked) {
alert("The check box is checked.");
} else {
alert("The check box is not checked.");
}
}
<input type="checkbox" value="yes" checked onclick="OnChangeCheckbox (this)" />
<label for="checkbox">uncheck box</label>
If your checkboxes and textboxes have something in common then you can do something like this:
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" />
<input type="text" id="txt1" />
<input type="text" id="txt2" />
<input type="text" id="txt3" />
<input type="text" id="txt4" />
<script>
function myFunction(el) {
var txt = document.getElementById(el.id.replace('chk', 'txt'));
if(el.checked) {
txt.value = 'checked';
}
else
txt.value = 'unchecked';
}
</script>
function myFunction(el) {
var txt = document.getElementById(el.id.replace('chk', 'txt'));
if(el.checked) {
txt.value = 'checked';
}else{
txt.value = 'unchecked';
}
}
<div>
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" />
<input type="text" id="txt1" />
</div>
<div>
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" />
<input type="text" id="txt2" />
</div>
<div>
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" />
<input type="text" id="txt3" />
</div>
<div>
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" />
<input type="text" id="txt4" />
</div>
You can create separate functions
function OnChangeCheckbox1(checkbox) {
..
}
<input type="checkbox" value="yes" checked onclick="OnChangeCheckbox1(this)" />
<label for="checkbox">uncheck box</label>
function OnChangeCheckbox2(checkbox) {
..
}
<input type="checkbox" value="yes" checked onclick="OnChangeCheckbox2 (this)" />
<label for="checkbox">uncheck box</label>
Update Answer
hi, i just update my answer, so your function run if unchecked and get the value of checkbox
<input type="checkbox" checked value="1" onclick="myFunction(this)" />
<input type="checkbox" checked value="2" onclick="myFunction(this)" />
<input type="checkbox" checked value="3" onclick="myFunction(this)" />
<input type="checkbox" checked value="4" onclick="myFunction(this)" />
<script>
function myFunction(e) {
if(e.checked == false) {
alert('this box unchecked | value = ' + e.value);
}
}
</script>
<div class="check_filter">
<div id="filter">
<input type="checkbox" id="check1" /><label for="check1">XYZ</label>
<input type="checkbox" id="check2" /><label for="check2">WAS</label>
<input type="checkbox" id="check3" /><label for="check3">DEF</label>
</div>
</div>
Js code :
$(document).ready(function() {
$(":checkbox").click(function(){
var id = $(this).attr('id');
var isChecked = $(this).attr('checked'));
if(isChecked == false){
switch (id) {
case check1:
txtbox1();
break;
case check2:
txtbox2();
break;
default:
defaultFunction();
}
}
});
});
I am a newbie in Javascript and can't figure out how to make my function work for both radio buttons and textfields.
Below is the HTML code for the form
<form action="sendmail.php" method="post" name="cascader"
onsubmit="prepareEventHandlers()" id="cascader">
<div class="TargetCenter"> <p><strong><span class="asterisk">*</span>Target Center</strong> </p>
<label>
<input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />
All Countries</label>
<label>
<input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />
France</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Bolivia" id="CheckboxGroup1_1" />
Bolivia</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="North America" id="CheckboxGroup1_2" />
North America</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="United Kingdom" id="CheckboxGroup1_3" />
United Kingdom</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Baltics" id="CheckboxGroup1_4" />
Baltics</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Slovakia" id="CheckboxGroup1_5" />
Slovakia</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Sweden" id="CheckboxGroup1_6" />
Sweden</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Switzerland" id="CheckboxGroup1_7" />
Switzerland</label>
<br /> </div> <!--end of Cascade Target--> <div class="CascadeCategory"> <strong>
<span class="asterisk">*</span>Cascade Category: </strong> <label>
<input type="radio" name="cascadeCategory" value="Process" id="CascadeCategory_0" />
Process</label> <label>
<input type="radio" name="cascadeCategory" value="Training" id="CascadeCategory_1" />
Training</label> <label>
<input type="radio" name="cascadeCategory" value="Knowledge" id="CascadeCategory_2"/> Knowledge</label> <br /> </div> <!--end
of Cascade Category--> <div class="ProcessTitle"><strong><span
class="asterisk">*</span>Process Title: <input name="textfld"
type="text" id="processTitle" iname="processTitle"
onkeypress="checkFieldValue()" /> </strong><span
id="errorMessage"></span></div> <!--end of Process Title--> <div
class="CascadeType"> <strong><span class="asterisk">*</span>Cascade
Type:</strong> <label> <input type="radio" name="cascadeType"
value="Release" /> Release</label> <label>
<input type="radio" name="cascadeType" value="Update" id="CascadeType_1" />
Update</label> <label>
<input type="radio" name="cascadeType" value="Reminder" id="CascadeType_2" />
Reminder</label> <br /> </div> <!--end of Cascade Type--> <div class="QuickDescr"> <strong><span class="asterisk">*</span>Quick
Description: </strong><br /> <br /><textarea name="textfld" cols="70%"
rows="5" id="quickDescr"></textarea><span id="errorMessage2"></span>
</div> <!--end of Quick Description--> <div class="Details">
<strong><span class="asterisk">*</span>Details: </strong><br /><br/>
<textarea name="details" cols="70%" rows="10" id="details"></textarea> </div>
<!--end of Description--> <div class="DueDate"> <strong><span class="asterisk">*</span>Due
Date:</strong> <input type="text" class="Due" name="DueDate"
placeholder="mm.dd.yyyy" /> <span
class="DueDateFormat">(mm.dd.yyyy)</span></div> <!--end of Due date-->
<br /> <br /> <br /> <input name="Submit" type="submit"
class="CascadeButton" value="Send Cascade" />
<input type="reset" value="Clear Fields" class="ResetButton" />
</form>
Below is the Javascript I applied for the processTitle textfield.
function prepareEventHandlers() {
document.getElementById("cascader").onsubmit = function() {
// prevent a form from submitting if no email.
if (document.getElementById("processTitle").value == "") {
document.getElementById("errorMessage").innerHTML = "Please enter a value";
// to STOP the form from submitting
window.scrollTo(0, 0);
document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
// to turn the field background color
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
};
}
// when the document loads
window.onload = function() {
prepareEventHandlers();
};
// Changes the field color onFocus
function checkFieldValue() {
if (document.getElementById("processTitle").value != "") {
document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
document.getElementById("errorMessage").innerHTML = "";
}
else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
}
I've added a little function to check if one of the radio buttons is selected. See checkRequiredRadioButtons at the bottom of the javascript. Currently I just linked it to your existing validation-failure code.
function prepareEventHandlers() {
document.getElementById("cascader").onsubmit = function() {
// prevent a form from submitting if no email.
if (document.getElementById("processTitle").value == "" || !checkRequiredRadioButtons('cascadeType')) {
document.getElementById("errorMessage").innerHTML = "Please enter a value";
// to STOP the form from submitting
window.scrollTo(0, 0);
document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
// to turn the field background color
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
};
}
// when the document loads
window.onload = function() {
prepareEventHandlers();
};
// Changes the field color onFocus
function checkFieldValue() {
if (document.getElementById("processTitle").value != "") {
document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
document.getElementById("errorMessage").innerHTML = "";
} else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
}
function checkRequiredRadioButtons(buttonsName) {
var buttonSet = document.getElementsByName(buttonsName);
for(i = 0; i < buttonSet.length; i++){
if(buttonSet[i].checked == true)
return true;
}
return false;
}
<form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader">
<div class="TargetCenter">
<p><strong><span class="asterisk">*</span>Target Center</strong>
</p>
<label>
<input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />All Countries</label>
<label>
<input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />France
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Bolivia" id="CheckboxGroup1_1" />Bolivia
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="North America" id="CheckboxGroup1_2" />North America</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="United Kingdom" id="CheckboxGroup1_3" />United Kingdom</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Baltics" id="CheckboxGroup1_4" />Baltics
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Slovakia" id="CheckboxGroup1_5" />Slovakia
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Sweden" id="CheckboxGroup1_6" />Sweden
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Switzerland" id="CheckboxGroup1_7" />Switzerland
</label>
<br />
</div>
<!--end of Cascade Target-->
<div class="CascadeCategory"> <strong>
<span class="asterisk">*</span>Cascade Category: </strong>
<label>
<input type="radio" name="cascadeCategory" value="Process" id="CascadeCategory_0" />Process
</label>
<label>
<input type="radio" name="cascadeCategory" value="Training" id="CascadeCategory_1" />Training
</label>
<label>
<input type="radio" name="cascadeCategory" value="Knowledge" id="CascadeCategory_2" />Knowledge</label>
<br />
</div>
<!--end
of Cascade Category-->
<div class="ProcessTitle"><strong><span
class="asterisk">*</span>Process Title: <input name="textfld"
type="text" id="processTitle" iname="processTitle"
onkeypress="checkFieldValue()" /> </strong><span id="errorMessage"></span>
</div>
<!--end of Process Title-->
<div class="CascadeType"> <strong><span class="asterisk">*</span>Cascade
Type:</strong>
<label>
<input type="radio" name="cascadeType" value="Release" />Release</label>
<label>
<input type="radio" name="cascadeType" value="Update" id="CascadeType_1" />Update
</label>
<label>
<input type="radio" name="cascadeType" value="Reminder" id="CascadeType_2" />Reminder
</label>
<br />
</div>
<!--end of Cascade Type-->
<div class="QuickDescr"> <strong><span class="asterisk">*</span>Quick
Description: </strong>
<br />
<br />
<textarea name="textfld" cols="70%" rows="5" id="quickDescr"></textarea><span id="errorMessage2"></span>
</div>
<!--end of Quick Description-->
<div class="Details">
<strong><span class="asterisk">*</span>Details: </strong>
<br />
<br/>
<textarea name="details" cols="70%" rows="10" id="details"></textarea>
</div>
<!--end of Description-->
<div class="DueDate"> <strong><span class="asterisk">*</span>Due
Date:</strong>
<input type="text" class="Due" name="DueDate" placeholder="mm.dd.yyyy" /> <span class="DueDateFormat">(mm.dd.yyyy)</span>
</div>
<!--end of Due date-->
<br />
<br />
<br />
<input name="Submit" type="submit" class="CascadeButton" value="Send Cascade" />
<input type="reset" value="Clear Fields" class="ResetButton" />
</form>
If you're trying to dynamically determine whether you have a textbox or a radio button, you can call Element.getAttribute('type') and compare. As in:
var allInputs = document.getElementsByTagName('input');
for(i = 0; i < allInputs.length; i++){
if(allInputs[i].getAttribute('type') == 'radio'){
//Do radio button handling
} else if(allInputs[i].getAttribute('type') == 'text'){
//Do textbox handling
}
}
However, if you do that you need to be aware that for radio buttons you're going to iterate over all the radio buttons in the group, checked and unchecked alike. As well as your submit and reset buttons.
Maybe you should try the javascript getElementsByTagName() method:
function myFunction() {
var x = document.getElementsByTagName("input");
for (var i=0; i<x.length; i++){
if(x[i].value==""){
x[i].style.backgroundColor="red";
}
}
}
i am trying to output form values with inner.html
I got 2 problems with my checkboxes:
1. if i check more then 1 checkbox, only one is outputted
2. if no checkbox is checked, the input from other fields are also not outputted
How can i fix this problem?
<script>function changeText(){
var userInputname = document.getElementById('name').value;
var userInputcolor = document.querySelector('.color:checked').value;
document.getElementById('output1').innerHTML = userInputname;
document.getElementById('output2').innerHTML = userInputcolor;
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="text" name="name" id="name" />
<br /><br />
<input type="checkbox" name="color" class="color" value="green">Green<br />
<input type="checkbox" name="color" class="color" value="yellow">Yellow<br />
<input type="checkbox" name="color" class="color" value="red">Red<br />
<input type="checkbox" name="color" class="color" value="blue">Blue<br />
<br /><br />
<input type="submit" value="Output" />
<br /><br />
<b id='output1'></b><br />
<b id='output2'></b><br />
document.querySelector only gets one single element, the first one encountered, you'd use document.querySelectorAll to get all matching elements, and you can convert that to an array and use map to return a concantenated string of the values, like this :
<script>function changeText(){
var userInputname = document.getElementById('name').value;
var userInputcolor = Array.prototype.slice.call(document.querySelectorAll(".color:checked")).map(function(el) {
return el.value;
}).join(', ')
document.getElementById('output1').innerHTML = userInputname;
document.getElementById('output2').innerHTML = userInputcolor;
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="text" name="name" id="name" />
<br /><br />
<input type="checkbox" name="color" class="color" value="green">Green<br />
<input type="checkbox" name="color" class="color" value="yellow">Yellow<br />
<input type="checkbox" name="color" class="color" value="red">Red<br />
<input type="checkbox" name="color" class="color" value="blue">Blue<br />
<br /><br />
<input type="submit" value="Output" />
<br /><br />
<b id='output1'></b><br />
<b id='output2'></b><br />
FIDDLE