Demo
Trying to change the input ID: List from A to B, but its not changing.
I am planning on creating many datalist with PHP from MySQL,
Select Company name, and see their employees in next list.
HTML:
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
JAVASCRIPT:
function change() {
console.log("Started");
var x = document.getElementById('A').value;
document.getElementById('List').list = x;
var check = document.getElementById('List').list
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
Thank you, its now working.
Working
According to the Mozilla Developer Network docs, the list attribute is read-only and actually returns a reference to a DOM element (like a <datalist>):
list [Read only]
HTMLElement object: Returns the element pointed by the list attribute.
The property may be null if no HTML element found in the same tree.
Thus, you need to use setAttribute to set the list by id, and then use element.list.id to retrieve the correct value for check.
function change() {
console.log("Started")
var x = document.getElementById('A').value
document.getElementById('List').setAttribute('list', x)
var check = document.getElementById('List').list.id
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
}
}
change List:
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="A" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
Since list is not a standard attribute, direct refering with the dot notation won't work. Use getAttribute and setAttribute functions instead.
function change() {
console.log("Started");
var x = document.getElementById('C'),
list = document.getElementById('List'),
check = list.getAttribute(list);
list.setAttribute('list', x);
if (check === x.getAttribute('list')) {
console.log("Complete");
} else {
console.log("Failed");
}
}
<input type="text" id="List" list="A">
<br>
<br>
<input type="text" id="C" value="B">
<br>
<button onclick="change()">
Change List
</button>
<datalist id="A">
<option value="None">
<option value="1">
<option value="2">
</datalist>
<datalist id="B">
<option value="3">
<option value="4">
</datalist>
Javascript
function change() {
document.getElementById('List').setAttribute('list', document.getElementById('A').id);
}
You need to set the value property on the dom element
document.getElementById('List').value = x;
var check = document.getElementById('List').value
if (check === x) {
console.log("Complete");
} else {
console.log("Failed");
console.log(check);
}
}
Related
I can't seem to figure out how to sum the values of various field types in a form. I have some select fields like this:
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
And some radio buttons:
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
But how would I add the selections all up? I can find solutions for adding values of just inputs, or just radios, or just selects. But not all together.
I'd use jQuery if I have to.
[EDIT] I should have said, I'd like to output the total value to the user, perhaps inside a element.
Could clean this up a bit, but an example of using the FormData interface to add up all values in a form: https://developer.mozilla.org/en-US/docs/Web/API/FormData
function getValues() {
let myForm = document.getElementById('myForm');
let formData = new FormData(myForm);
let total = 0;
for (var value of formData.values()) {
total += parseInt(value);
}
document.getElementById("total").innerHTML = total;
console.log(total);
}
<form id="myForm" name="myForm">
<div>
<label for="age">What is your age?</label>
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
</div>
<div>
<label for="riskSmoke">Do you smoke?</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</div>
</form>
<button onclick="getValues()">Get Values</button>
<p>Total:</p>
<div id="total"></div>
You can use constructor FormData.
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
You could add a key/value pair to this using FormData.append:
formData.append('username', 'Chris');
I assume that you mean adding the values of the selected elements and that you use some trigger in this case I use a button. To make it work select options that have values
Please try this option
const button = document.querySelector("button");
button.addEventListener("click", () => {
const age = document.querySelector("select");
const riskSmoke = document.querySelector('input[name="riskSmoke"]:checked');
if (age && age.value && riskSmoke) {
const ageValue = +age.value;
const riskSmokeValue = +riskSmoke.value;
console.log(ageValue + riskSmokeValue);
}
});
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label><input type="radio" name="riskSmoke" value="2" /> Yes</label><br />
<label><input type="radio" name="riskSmoke" value="0" /> No</label>
<button>Click</button>
Without jQuery and for selecting specific values:
function getValues() {
var ageValue = Number(document.querySelector("select[name=age]").value);
console.log('age value: ' + ageValue);
var smokeValue = Number(document.querySelector('input[name="riskSmoke"]:checked').value);
console.log('smoke value: ' + smokeValue);
console.log('age + smoke: ' + (ageValue + smokeValue));
}
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<p>
<button onclick="getValues()">Get Values</button>
jQuery seems to be a bit of a overkill. In order to get the sum of the options and inputs, you may first get the value of the option in the select tag, and then add to the value of the selected radio input as such:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Title Here</title>
</head>
<body>
<select name="age" id="someId">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label><br>
<button onclick="CalculateValue()">Calculate</button>
<script>
let ageRangePicker = null, riskSmokeOptions = null;
function CalculateValue(){
ageRangePicker = document.getElementById("someId");
if(ageRangePicker.value !== ""){
let sum = Number(ageRangePicker.value);
riskSmokeOptions = document.getElementsByName("riskSmoke")
for(i = 0; i < riskSmokeOptions.length; i++) {
if(riskSmokeOptions[i].checked)
sum += Number(riskSmokeOptions[i].value);
}
alert("Your risk is: " + sum);
}
else{
alert("Select an age range");
}
}
</script>
</body>
</html>
I wrap in a form with an ID and sum on all input, making sure only to count checked radios and checkboxes
const sumValues = () => {
let val = 0;
$("#myForm :input").each(function() {
if (this.type === "radio" || this.type === "checkbox")
val += this.checked ? +this.value : 0;
else val += +this.value; // cast to number
})
$("#total").text(val)
};
$(function() {
$("#myForm").on("change", sumValues).change(); //when page loads
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
Plain JS
const sumValues = () => {
let val = 0;
[...document.getElementById("myForm").querySelectorAll("input, select, textarea")].forEach(function(elem) {
if (elem.type === "radio" || elem.type === "checkbox")
val += elem.checked ? +elem.value : 0;
else val += +elem.value; // cast to number
})
document.getElementById("total").textContent = val;
};
window.addEventListener("load", function() {
document.querySelector("#myForm").addEventListener("change", sumValues)
sumValues()
})
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
With jQuery, you can listen for the change event and use both the jQuery .serializeArray() and the array .reduce() method to get the total:
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//output to a predefined element
$('#output').text( totalScore );
})
.change();
Here is how you may define an output element:
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Note that this will give a running total and there's no need to click any button or to trigger any event other then the actions needed to make choices on the various form elements.
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//console.log( totalScore );
$('#output').text( totalScore );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</form>
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Put a button below at the bottom of your HTML and make a function something like this:
const radioControls = document.querySelectorAll('.radio-btn');
const selectControl = document.querySelectorAll('.select');
let dataTransferObject = {
radioValue: 0,
selectValue: 0
};
let sum = 0;
function collectValues() {
for(let control of radioControls) {
if (control.checked) {
dto.radioValue = control.value
}
}
dto.selectValue = selectControl[0].value;
for(let attr of Object.values(dto)) {
sum += parseInt(attr);
}
}
Then your button simply calls this function, I would imagine this would all be contained in a form of some sort:
<button onclick="collectValues()">Submit</button>
Now the variable sum holds the accumulated value.
I need to add some values from a HTML5 DataList to a <select multiple> control just with Javascript. But I can't guess how to do it.
This is what I have tried:
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option label="Red" value="1">
<option label="Yellow" value="2">
<option label="Green" value="3">
<option label="Blue" value="4">
</datalist>
<button type="button" onclick="AddValue(document.getElementById('AllColors').value, document.getElementById('AllColors').text);">Add</button>
<select id="Colors" size="3" multiple></select>
function AddValue(Value, Text){
//Value and Text are empty!
var option=document.createElement("option");
option.value=Value;
option.text=Text;
document.getElementById('Colors').appendChild(option);
}
This should work. I have moved the value selection logic into the method itself.
You will only get the value from the input. You will need to use the value to select the label from the datalist.
function AddValue(){
const Value = document.querySelector('#SelectColor').value;
if(!Value) return;
const Text = document.querySelector('option[value="' + Value + '"]').label;
const option=document.createElement("option");
option.value=Value;
option.text=Text;
document.getElementById('Colors').appendChild(option);
}
Here is the working demo.
You can check the trimmed value of the input. If value is not empty then you can get the selected data list option by matching the value attribute with querySelector().
Try the following way:
function AddValue(el, dl){
if(el.value.trim() != ''){
var opSelected = dl.querySelector(`[value="${el.value}"]`);
var option = document.createElement("option");
option.value = opSelected.value;
option.text = opSelected.getAttribute('label');
document.getElementById('Colors').appendChild(option);
}
}
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option label="Red" value="1"></option>
<option label="Yellow" value="2"></option>
<option label="Green" value="3"></option>
<option label="Blue" value="4"></option>
</datalist>
<button type="button" onclick="AddValue(document.getElementById('SelectColor'), document.getElementById('AllColors'));">Add</button>
<select id="Colors" size="3" multiple></select>
To get the selected options's ID in datalist, you can use this code too.
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option value="Red" id=1></option>
<option value="Yellow" id=2></option>
<option value="Green" id=3></option>
<option value="Blue" id=4></option>
</datalist>
<script>
$("#SelectColor").change(function(){
var el=$("#SelectColor")[0]; //used [0] is to get HTML DOM not jquery Object
var dl=$("#AllColors")[0];
if(el.value.trim() != ''){
var opSelected = dl.querySelector(`[value="${el.value}"]`);
alert(opSelected.getAttribute('id'));
}
});
</script>
I want to validate the select method with submit type button. I have created a form and under that, I have created the select method and given some options. By submit type, the onClick should validate my submit type with the options in the select method. How can I assign the value of option
to var t based on select?
According to the select option my var t should be changed.
If the value is volvo then it should print val11, similarly Saab= val14, opel= val82, Audi= val34
<select name="carlist" class="temp>
<option value="10">Volvo</option>
<option value="20">Saab</option>
<option value="30">Opel</option>
<option value="45">Audi</option>
</select>
<input type="submit" class="temp" value="submit the answer">
<script>
var t;
if () {
t=value;
} else if () {
t=value;
} else if () {
t=value;
}else {
t=value;
}
</script>
You can call a function on clicking the button. Inside the function get the text of the selected option:
function getValue(){
var el = document.querySelector('.temp');
var val = el.options[el.selectedIndex].text;
var t;
if(val == "Volvo")
t = 'val11';
else if(val == "Saab")
t = 'val14';
if(val == "Opel")
t = 'val82';
else if(val == "Audi")
t = 'val34';
alert(t);
}
<form>
<select name="carlist" class="temp">
<option value="10">Volvo</option>
<option value="20">Saab</option>
<option value="30">Opel</option>
<option value="45">Audi</option>
</select>
<input onclick="getValue()" type="submit" class="temp" value="submit the answer">
</form>
You can also think of using data attribute which is more cleaner and simpler:
function getValue(){
var el = document.querySelector('.temp');
var t = el.options[el.selectedIndex].getAttribute('data-val');
alert(t);
}
<form>
<select name="carlist" class="temp">
<option value="10" data-val="val11">Volvo</option>
<option value="20" data-val="val14">Saab</option>
<option value="30" data-val="val82">Opel</option>
<option value="45" data-val="val34">Audi</option>
</select>
<input onclick="getValue()" type="submit" class="temp" value="submit the answer">
</form>
You can do a few things, here's the simplest I could get away with.
function submitForm() {
const value = document.querySelector('[name="carlist"').value;
console.log(value);
return false; // to prevent it navigating away.
}
<form onsubmit="submitForm()">
<select name="carlist" class="temp">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
<input type="submit" class="temp" value="submit the answer">
You can also have some validation running earlier, e.g. on change:
/**
* This function runs on form submit.
*/
function submitForm(event) {
const value = document.querySelector('[name="carlist"').value;
console.log(value);
// to prevent it navigating away.
event.preventDefault();
return false;
}
/**
* This function runs on selection change
*/
function validateCar(changeEvent) {
console.log('Change');
// do something with changeEvent
}
<form onsubmit="submitForm(event)">
<select name="carlist" class="temp" onchange="validateCar(event)">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
<input type="submit" class="temp" value="submit the answer">
You can set an id attribute on the select element and then access it through a querySelector or getElementById.
<form id="carForm">
<select name="carlist" class="temp" id="car">
<option value="val11">Volvo</option>
<option value="val14">Saab</option>
<option value="val82">Opel</option>
<option value="val34">Audi</option>
</select>
</form>
let carForm = document.getElementById('carForm');
carForm.onsubmit = function(event) {
var t = document.getElementById('car');
...
}
See codepen example
I have the following code that is not working the way i want it to, apparently, am trying to multiply select option data attributes with input text area values but instead select option value are being used. I need to figure out why its so.
Here is my code;
<input id="count" min="1" value="1" class ="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class ="txtMult" name="txtEmmail"/>
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
$(function(){
$('.txtMult').change(function(){
var p=$(this).parent().parent()
var m=p.find('input.txtMult')
var mul=parseInt($(m[0]).val()*$(m[1]).val()).toFixed(2)
var res=p.find('.multTotal')
res.html(mul);
var total=0;
$('.multTotal').each(function(){
total+=parseInt($(this).html());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(function() {
calcVal();
});
function calcVal(){
$(this).data('cubics')*$('.multTotal').html();
$("#grandTotal").html($(this).data('cubics')*$('.multTotal').html())
}
// call on document load
calcVal();
Don't use .html() to get the values, use .text() instead.
You need to get the selected option using this:
$("#grandTotal").html($(this).children(':checked')
$(function() {
$('.txtMult').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val() * $(m[1]).val()).toFixed(2)
var res = p.find('.multTotal')
res.html(mul);
var total = 0;
$('.multTotal').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(calcVal);
function calcVal() {
$("#grandTotal").html($(this).children(':checked').data('cubics') * $('.multTotal').text().trim())
}
// call on document load
calcVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input id="count" min="1" value="1" class="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class="txtMult" name="txtEmmail" />
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
</div>
</div>
im trying to access an attribute that i created in a select list.
<script language="JavaScript">
function updateUrl()
{
var newUrl=document.getElementById('test').car;
alert(newUrl);
}
</script>
<input type="text" id="test" car="red" value="create Attribute test" size="40"/>
<input type="button" value="submit" onclick="updateUrl();">
it keep giving me undefined. how do i get the string red from attribute car?
edit. i tried it with the select list it alerts null now
<select name= "test" id= "test" onChange= "updateUrl()">
<option value="1" selected="selected" car="red">1</option>
<option value="2" car="blue" >2</option>
<option value="3" car="white" >3</option>
<option value="4" car="black" >4</option>
</select>
Try this:
var newUrl = document.getElementById('test').getAttribute('car');
EDIT
For the <select>, you have to look into the selected <option> element, not the <select> itself:
var select = document.getElementById('test');
select.options[select.selectedIndex].getAttribute('car');