Checkbox selection based on name is prompting other checkbox options - javascript

I am attempting to set the value of newStatus or usedStatus if any of the options for either is selected, but for only the ones that are selected.
As of now, if you select "New mowers" and then click on one of its options, you will see in the console that New Selection1 and Used Selection is displayed in the console. For this example and the functionality, only New Selection1 should be showing.
The following if statements are controlling it:
if ("input:checkbox[name=newMowerOption]:checked") {
newStatus = '1';
console.log('New Selection' + newStatus);
}
if ("input:checkbox[name=usedMowerOption]:checked") {
usedStatus = '1';
console.log('Used Selection' + usedStatus);
}
You can see that I am checking for the specific checkboxes based on the name, so I am unsure why if you select a new mower option that the used is also selected.
Anyone have an idea?
var newStatus = ''; //Telling whether new is selected
var usedStatus = ''; //Telling whether used is selected
var newSelPush = '';
var usedSelPush = '';
$('.equipmentOptionCont').change(function() {
var newSel = [];
var usedSel = [];
//Get new mower options
$("input:checkbox[name=newMowerOption]:checked").each(function(){
newSel.push($(this).val());
newSelPush = newSel.join(', ');
});
//Get used mower options
$("input:checkbox[name=usedMowerOption]:checked").each(function(){
usedSel.push($(this).val());
usedSelPush = usedSel.join(', ');
});
//Find out if new/used mower option is selected and then create variable showing 1 if true
if ("input:checkbox[name=newMowerOption]:checked") {
newStatus = '1';
console.log('New Selection' + newStatus);
}
if ("input:checkbox[name=usedMowerOption]:checked") {
usedStatus = '1';
console.log('Used Selection' + usedStatus);
}
$('#newSel').html(newSelPush);
$('#usedSel').html(usedSelPush);
});
$('#newAllOptions').click(function() {
$('input[name=newMowerOption').toggle().prop('checked', true);
});
$('#usedAllOptions').click(function() {
$('input[name=usedMowerOption').toggle().prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>New Mowers</label>
<input type="radio" name="notifymethod" id="newMowerSelect" class="equipmentMainSel">
<label>Used Mowers</label>
<input type="radio" name="notifymethod" id="usedMowerSelect" class="equipmentMainSel">
<div id="newMowerOptions" class="equipmentOptionCont">
<p>New Mower Options</p>
<label>Ferris</label>
<input type="checkbox" name="newMowerOption" value="Ferris">
<label>Wright</label>
<input type="checkbox" name="newMowerOption" value="Wright">
</div>
<div id="usedMowerOptions" class="equipmentOptionCont">
<p>Used Mower Options</p>
<label>Toro</label>
<input type="checkbox" name="usedMowerOption" value="Toro">
<label>John Deere</label>
<input type="checkbox" name="usedMowerOption" value="John Deere">
</div>

Changed logic to get the desired results.
var newStatus = ''; //Telling whether new is selected
var usedStatus = ''; //Telling whether used is selected
var newSelPush = '';
var usedSelPush = '';
$('.equipmentOptionCont').change(function() {
var newSel = [];
var usedSel = [];
//Get new mower options
$("input:checkbox[name=newMowerOption]:checked").each(function(){
newSel.push($(this).val());
newSelPush = newSel.join(', ');
});
//Get used mower options
$("input:checkbox[name=usedMowerOption]:checked").each(function(){
usedSel.push($(this).val());
usedSelPush = usedSel.join(', ');
});
var radioSelID = $("input:radio[name=notifymethod]:checked").attr('id');
if(newSel.length && radioSelID == "newMowerSelect") {
newStatus = '1';
console.log('New Selection' + newStatus);
}
if(usedSel.length && radioSelID == "usedMowerSelect") {
usedStatus = '1';
console.log('Used Selection' + usedStatus);
}
$('#newSel').html(newSelPush);
$('#usedSel').html(usedSelPush);
});
$('#newAllOptions').click(function() {
$('input[name=newMowerOption').toggle().prop('checked', true);
});
$('#usedAllOptions').click(function() {
$('input[name=usedMowerOption').toggle().prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>New Mowers</label>
<input type="radio" name="notifymethod" id="newMowerSelect" class="equipmentMainSel">
<label>Used Mowers</label>
<input type="radio" name="notifymethod" id="usedMowerSelect" class="equipmentMainSel">
<div id="newMowerOptions" class="equipmentOptionCont">
<p>New Mower Options</p>
<label>Ferris</label>
<input type="checkbox" name="newMowerOption" value="Ferris">
<label>Wright</label>
<input type="checkbox" name="newMowerOption" value="Wright">
</div>
<div id="usedMowerOptions" class="equipmentOptionCont">
<p>Used Mower Options</p>
<label>Toro</label>
<input type="checkbox" name="usedMowerOption" value="Toro">
<label>John Deere</label>
<input type="checkbox" name="usedMowerOption" value="John Deere">
</div>
Old answer:
Your if statements were just checking a string, which in JavaScript was always returning true and thus both were being printed. I changed it to check the actual property instead, there a couple different ways to do this but the following does what you want.

Related

How do I get the Onkey Function to copy the value of a input textfield to the other 3 textfields

This is the Java Script I'm using. I can enter in the proceduredate and it copies to proceduredate2 but not 3 and 4--Same with Procedure
function copyTextAreaValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
console.log('no dest element ' + destIds[i]);
}
}
}
}
Link to JSFiddle with full code
Your question id not clear to me. However, all I understood is you want to copy text from your current text input to other three text input. If that is true, then you can have your solution here. Please, checkout the snippet below.
let el = document.getElementById('field_1');
function copyTextValue() {
let elVal = el.value;
document.getElementById("field_2").value = elVal;
document.getElementById("field_3").value = elVal;
document.getElementById("field_4").value = elVal;
}
copyTextValue();
el.oninput = copyTextValue;
el.onchange = copyTextValue;
Today's Date: <input id="field_1" value=""/><br/>
Procedure Date: <input id="field_2" value=""/> <br/>
Date of Procedure: <input id="field_3" value=""/> <br/>
Surgery Date: <input id="field_4" value=""/> <br/>
function copyTextfieldValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
//console.log('no dest element ' + destIds[i]);
}
}
}
}
<input id="t1">
<input id="t2">
<input id="t3">
<input id="t4">
<input type="button" value='copy' onclick="copyTextfieldValue('t1','t2,t3,t4');">
Your code seems to work fine. See the snippet.

Return CheckBox True False Status With jQuery Map

I am creating dynamic CheckBoxes using jQuery and by default, those are set to false status. Something as follows:
<input type="checkbox" class="cbCheck" value="false" />
So you can see no value or id is assigned there. Is it possible to just retrieve the true/false based on CheckBox checked/unchecked status something as follows using jQuery mapping?
string = $('input[type=checkbox]:checked').map(function (i, elements) {
return elements; //Here the elements like true or false, instead of elements.value
});
alert(string.join(','));
Expected Output: true, false, false, true (Based on user selection)
You can use the checked property.
const string = Array.from($('input[type=checkbox]')).map(function(element) {
return element.checked; //Here the elements like true or false, instead of elements.value
});
console.log(string.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" checked/>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked/>
var checkboxes = [];
function createDynamicCheckBoxes() {
if (checkboxes.length != 0)
return;
var numberOfBoxes = parseInt(Math.random() * 10) + 1;
for (var i = 0; i < numberOfBoxes; i++) {
var checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("value", "false");
var number = document.createElement('label');
number.innerText = "(" + (checkboxes.length+1) + ") ";
document.getElementById("container").appendChild(number);
document.getElementById("container").appendChild(checkbox);
document.getElementById("container").appendChild(document.createElement('br'));
checkboxes.push(checkbox);
}
}
function logValues(){
for(var i=0; i<checkboxes.length;i++){
console.log("Checkbox (" + (i+1) + ") is set to " + checkboxes[i].checked);
}
}
<button onclick="createDynamicCheckBoxes()">Generate Checkboxes</button>
<button onclick="logValues()">Log Values of Checkboxes</button>
<div id="container">
</div>
This is a pure JavaScript based snippet. You can do something like this!
The .checked property return check/uncheck status of checkbox. So you need to use it.
var string = $('[type=checkbox]').map(function (i, elements) {
return elements.checked;
}).toArray().join(",");
Also you can simplify the code
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
console.log(string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked />
<input type="checkbox" class="cbCheck" />

Persisting multiple checkbox states in session Storage

My program needs to store the value of multiple checkboxes in session Storage (checked or not checked), so that when the user returns to this page they are already checked or not checked. All the solutions to this problem that I have found involve the use of JQuery which we aren't supposed to use.
This is the HTML for the checkboxes
<fieldset>
<legend>Skills List</legend>
<p> <label for="teamwork">Teamwork</label>
<input type="checkbox" id="teamwork" name="Skill[]" value="Teamwork" checked="checked"/>
<label for="rubyskills">Ruby Experience</label>
<input type="checkbox" id="rubyskills" name="Skill[]" value="Rubyskills"/>
<label for="efficiency">Efficiency</label>
<input type="checkbox" id="efficiency" name="Skill[]" value="Efficiency"/>
<label for="communication">Communication</label>
<input type="checkbox" id="communication" name="Skill[]" value="Communication"/>
<label for="other">Other</label>
<input type="checkbox" id="other" name="Skill[]" value="other"/>
</p>
so, in vanilla JS this is how you would go about getting all of the checked inputs in your given fieldset. If you could update your question with a bit more detail and code on how you are saving to session storage I can help further.
let fieldset = document.getElementById("fieldset1") // get fieldset element
let p = fieldset.children[1]; // the p tag
let pchildren = p.children; // the contents of the p tag
let inputs = []; // where we will hold the input elements that are checked
for (let x = 0; x < pchildren.length; x++) { // looping through to get only the inputs that are checked
if (pchildren[x].nodeName == "INPUT" && pchildren[x].checked) {
inputs.push(pchildren[x]) // pushing into array
}
}
console.log(inputs);
Thanks but I solved it
function store_data() {
var teamwork = document.getElementById("teamwork").checked;
var rubyskills = document.getElementById("rubyskills").checked;
var efficiency = document.getElementById("efficiency").checked;
var communication = document.getElementById("communication").checked;
sessionStorage.setItem("teamwork", teamwork);
sessionStorage.setItem("ruby", rubyskills);
sessionStorage.setItem("efficiency", efficiency);
sessionStorage.setItem("communication", communication);
sessionStorage.setItem("other", other);
}
function prefill_form() {
if(sessionStorage.teamwork == "true") {
document.getElementById("teamwork").checked = true;
}
if(sessionStorage.ruby == "true") {
document.getElementById("rubyskills").checked = true;
}
if(sessionStorage.efficiency == "true") {
document.getElementById("efficiency").checked = true;
}
if(sessionStorage.communication == "true") {
document.getElementById("communication").checked = true;
}
if(sessionStorage.other == "true") {
document.getElementById("other").checked = true;
}
}

Change HTML tag with Javascript

I asking the user to select given emails, and getting them with javascript from a form on click.
If I have an href like
And I have a bunch of checkboxes for every email obtained from the database
Using javascript, how can I add this value into the emails="" tag by clicking the checkbox?
You can listen to change event for each checkbox to keep track of checked emails:
var boxes = document.querySelectorAll('input[name=email]');
var link = document.getElementById('myHref');
var emails = [];
boxes.forEach(box => box.addEventListener('change', function(e) {
var v = e.target.value;
if (e.target.checked === true) {
if (!emails.includes(v)) emails.push(v);
} else {
emails.splice(emails.indexOf(v), 1);
};
link.setAttribute('emails', emails.join(', '));
console.log(link.attributes.emails.value)
}))
<input type="checkbox" value="1#d.com" name="email">
<input type="checkbox" value="2#d.com" name="email">
<input type="checkbox" value="3#d.com" name="email">
Link
You can set a click event on the checkbox.
var arr_el = document.getElementsByClassName('check-boxes');
for(var i = 0; i < arr_el.length; i++){
arr_el[i].addEventListener('click', function(){
var el = document.getElementById('myHref');
var emails = el.getAttribute('emails');
var userSelectedEmail = this.value;
if(this.checked){
el.setAttribute('emails', emails + ';' + userSelectedEmail);
} else {
// debugger;
emails = emails.split(';');
var index = emails.indexOf(userSelectedEmail);
emails.splice(index, 1);
el.setAttribute('emails', emails.join(';'));
}
document.getElementById('emails').innerText = el.getAttribute('emails');
});
}
<html>
<head>
</head>
<body>
<a id="myHref" href="#" emails="test#email.com">Link</a>
<br>
<input class="check-boxes" type="checkbox" value="email2#gmail.com">email2#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email3#gmail.com">email3#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email4#gmail.com">email4#gmail.com<br>
<input class="check-boxes" type="checkbox" value="email5#gmail.com">email5#gmail.com<br>
<p id="emails"></p>
</body>
</html>

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

Categories

Resources