JS: Make checkboxes disabled if select is default value? - javascript

I have a set of checkboxes from
<input type="checkbox" name="parts_hoses" id="parts-cb1" value="1">
through id="parts-cb6"
I have a select box of #send-product
<select name="send_product" id="send-product">
<option value="wall-mounted" selected>Wall-mounted (Default)</option>
<option value="freestanding">Freestanding</option>
<option value="third_party">Third Party</option>
</select>
that when it is on its default value, "wall-mounted", the checkboxes are enabled (as they are by default), but when I switch that to another option in the list... I'd like to disable the checkboxes.
Here is my JS so far (doesn't work):
function switchProduct() {
var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
var selectBox = document.getElementById('send-product');
if (selectBox.value == 'wall-mounted') {
checkBoxes.disabled = false;
} else {
checkBoxes.disabled = true;
}
}
document.getElementById('send-product').addEventListener('change', switchProduct);
What am I doing wrong? Any help is appreciated!
Here's a fiddle: https://jsfiddle.net/cwkgsuq1/

You're missing to loop your checkboxes Array collection.
plain JS is not jQuery, therefore "checkBoxes.disabled = false;" will not work.
Instead:
for(var i=0; i<checkBoxes.length; i++) {
checkBoxes[i].disabled = false;
}
So your code simplified could look like:
function switchProduct() {
var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
var selectBox = document.getElementById('send-product');
for(var i=0; i<checkBoxes.length; i++) {
checkBoxes[i].disabled = selectBox.value == 'wall-mounted';
}
}
document.getElementById('send-product').addEventListener('change', switchProduct);
switchProduct();
<select name="send_product" id="send-product">
<option value="wall-mounted" selected>Wall-mounted (Default)</option>
<option value="freestanding">Freestanding</option>
<option value="third_party">Third Party</option>
</select><br><br>
<input type="checkbox" id="parts-cb1" value="1">
<br>
<input type="checkbox" id="parts-cb2" value="1">
<br>
<input type="checkbox" id="parts-cb3" value="1">

Related

How to get value from select box in html table

I'm trying to retrieve a value from a select box in my HTML table. How can I select the selected value?
What I've tried so far:
this.cells[14].innerHTML;
this.cells[14].children[0].innerhtml;
this.cells[14].children[0].innerText;
The last one .innerText returns all the items in my select box......
var table2 = document.getElementById('table_items_program');
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function () {
document.getElementById("id").value = this.cells[0].innerHTML;
document.getElementById("select").value = this.cells[14].children[0].innerText;
}
}
<td><select class="selectpicker" multiple>
<?php while ($row9 = mysqli_fetch_assoc($result9)):; ?>
<option value="<?php echo $row9['id']; ?>"><?php echo $row9['id'];?>
</option>
<?php endwhile; ?>
</select></td>
<input style="display: inline" id="id" name="id">
<input style="display: inline" id="select" name="select">
The selected value from my selection box in my HTML table
How can I select the selected value?
You can get the selected index with the method HTMLSelect​Element​.selected​Index
But if I understand your trouble. You try to get the current values of your select. So you need to get the value of your selected options.
You can do it like:
document.getElementById('mySelect').onchange = function() {
let options = this && this.options;
let selectedValues = []
for (var i = options.length; i--;) {
let opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
console.log(selectedValues)
}
<select id="mySelect" multiple>
<option value="a"> a </option>
<option value="b"> b </option>
<option value="c"> c </option>
</select>
Implementation into your code example
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function() {
document.getElementById("id").value = this.cells[0].innerHTML;
var options = this && this.cells[14].children[0].options;
var selectedValues = []
for (var i = options.length; i--;) {
var opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
document.getElementById("select").value = JSON.stringify(selectedValues);
}
}
so simple...
ShowSelected.onclick = function()
{
console.clear()
document.querySelectorAll('.selectpicker option:checked').forEach(opt=>console.log(opt.value))
}
.selectpicker {
vertical-align: text-top;
}
choose one or more :
<select class="selectpicker" multiple size=6 >
<option value="a"> A element</option>
<option value="b"> B element</option>
<option value="c"> C element</option>
<option value="d"> D element</option>
<option value="e"> E element</option>
<option value="f"> F element</option>
</select>
<button id="ShowSelected"> Show Selected</button>
Welcome to Stack Overflow!
So, your <select> has the class selectpicker. We can use this to select your <select>!
Try the following to get your value:
document.querySelector(".selectpicker").value;
Or, if you have multiple <select>'s, you can use
[...document.querySelectorAll(".selectpicker")].forEach(opt => {
console.log(opt.value)
});
Hope that clears things up a little.

Adding values from checkbox and dropdown select option

I would like to add the values from checkboxes and a dropdown menu using JavaScript (no JQuery).
My first question is how best to do this... my code is bellow.
Second question is are there disadvantages to using anonymous functions to do this?
Thank you!
https://jsfiddle.net/Buleria28/4ysvgkz8/
HTML
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum" > box 1
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum" > box 2
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum" > box 3
</label>
<br/><br/>
<select id="select" name ="select">
<option class="sum"></option>
<option value="1" class="sum">option 1</option>
<option value="2" class="sum">option 2</option>
<option value="5" class="sum">option 3</option>
</select>
<br/><br/>
Total: $<span id="payment-total">0</span>
JavaScript
/*To get checkbox values*/
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var checkAdd = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + checkAdd;
}
}
/*To get select values*/
var dropdown= document.getElementById("select");
for(j=0; j<dropdown.options.length;j++){
dropdown[j].onchange = function() {
if (dropdown[i].options.checked){
var selectAdd = dropdown.options[dropdown.selectedIndex].value;
total.innerHTML = parseFloat(total.innerHTML) + selectAdd;
}
}
}
Some things I want to point out:
Use addEventListener to bing event handlers
You can use anonymous functions but it's clearer when you declare it and give it a meaningful name
Don't keep total sum in the HTML element. Keep it in the variable and then insert it into HTML.
I would do it like that:
var checkboxes = document.querySelectorAll('.sum')
var select = document.querySelector('#select')
var total = document.querySelector('#payment-total')
var checkboxesTotal = 0
var selectTotal = 0
checkboxes.forEach(function(input) {
input.addEventListener('change', onCheckboxSelect)
})
select.addEventListener('change', onSelectChange)
function onCheckboxSelect(e) {
var sign = e.target.checked ? 1 : -1
checkboxesTotal += sign * parseInt(e.target.value, 10)
renderTotal()
}
function onSelectChange(e) {
var value = parseInt(e.target.value, 10)
if (!isNaN(value)) {
selectTotal = value
renderTotal()
}
}
function renderTotal() {
total.innerHTML = checkboxesTotal + selectTotal
}
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum"> box 1
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum"> box 2
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum"> box 3
</label>
<br/>
<br/>
<select id="select" name="select">
<option class="sum"></option>
<option value="1" class="sum">option 1</option>
<option value="2" class="sum">option 2</option>
<option value="5" class="sum">option 3</option>
</select>
<br/>
<br/> Total: $<span id="payment-total">0</span>
Here is a correction for JS regarding select element, I added inline comments, please check them for clarification:
/*To get select values*/
var dropdown = document.getElementById("select");
dropdown.onchange = function() {
var value = parseInt(this.value); // gets the selected value from "select" and tries to convert it to int
if(!isNaN(value)) { // if conversion is OK, i.e. it was a number
total.innerHTML = parseFloat(total.innerHTML) + value; // this line is copied from your previous code
}
}

jquery ajax loaded data option selection

Here is my html that will loaded with ajax call.
<select id="choice-id" name="choice_name">
<option value="2">2</option>
<option value="3" selected="">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div style="display: block;" id="select" class="other">
<input id="other-0" name="other_0" type="text" value="abc">
<input id="other-1" name="other_1" type="text" value="pqr">
<input id="other-2" name="other_2" type="text" value="rst">
</div>
here is my jquery for changing input field corresponding to option select. if i select option with value '6' it will generate 6 input field without any values.
$(document).on('change','#choice-id',function() {
var choicesizeSelected = $("#choice-id :selected").val();
$('.other').empty();
for(var i=0; i<choicesizeSelected; i++) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
this code is working perfectly. but if i select again default option 3, i want return default 3 input field with same values.
thanks in advance.
What you are doing is emptying the whole .other div.
Instead, compare if the number of inputs is bigger or smaller than selected.
If the selected number is bigger: add fields
If the selected number is smaller: remove fields
If the selected number is the same: do nothing
$(function() {
$('#choice-id').on('change', function() {
var newNum = $(this).find(':selected').val();
var oldNum = $('.other input').length;
if( oldNum > newNum ) {
var x = parseInt(newNum)+1;
$('.other input:nth-child(n+'+x+')').remove();
}
else if( oldNum < newNum ) {
for( var i=oldNum; i<newNum; i++ ) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
});
});
DEMO

Check if an item is not selected from a dropdown [duplicate]

This question already has answers here:
JavaScript - a way check if an option of the <select> tag is selected
(3 answers)
Closed 8 years ago.
I have a dropdown list that is generating dynamically using PHP. Its rendered HTML is something similar to below markup -
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
Using this markup, just I want to check whether item is selected or not using JavaScript. If it is not selected an item, then I need to get an alert message.
I tried it something like this. But I can not get it to work.
JavaScript -
var email = document.getElementById("email");
var selectedValue = email.options[email.selectedIndex].value;
if (selectedValue == '') {
alert("Please select a email");
}
Hope somebody may help me out.
Thank you.
You should listen to the change event of the select element and then parse the value of the selected option as an integer (parseInt(email.options[email.selectedIndex].value, 10)):
Example Here
var email = document.getElementById("email");
email.addEventListener('change', function (e) {
var selectedValue = parseInt(email.options[email.selectedIndex].value, 10);
if (selectedValue === 7) {
alert("Please select a email");
}
});
var email = document.getElementById("email");
email.addEventListener('change', function (e) {
var selectedValue = parseInt(email.options[email.selectedIndex].value, 10);
if (selectedValue === 7) {
alert("Please select a email");
}
});
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
... since you're validating whether an option is selected, you would use something more along these lines:
Example Here
var email = document.getElementById("email"),
validationButton = document.getElementById('validationButton');
validationButton.addEventListener('click', function (e) {
var selectedValue = email.options[email.selectedIndex] ? email.options[email.selectedIndex].value : null;
if (!selectedValue) {
alert("Please select a email");
}
});
var email = document.getElementById("email"),
validationButton = document.getElementById('validationButton');
validationButton.addEventListener('click', function (e) {
var selectedValue = email.options[email.selectedIndex] ? email.options[email.selectedIndex].value : null;
if (!selectedValue) {
alert("Please select a email");
}
});
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
<button id="validationButton">Check if selected</button>

Dynamically adding textbox in Html

function change() {
var select = document.getElementById("slct");
var divv = document.getElementById("container");
var value = select.value;
for (i = 0; i <value; i++) {
toAppend += "<input type='textbox' >";
}
divv.innerHTML=toAppend;`enter code here`
return;
}
I Have this code and I am calling it by dropdown menu
<select id="slct" onchange="change();">
<option value="0"> select value </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
but its not showing anything
Declare var toAppend='' before the for loop

Categories

Resources