Use created attribute with javascript in select list - javascript

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');

Related

How to select/unselect select options with checkboxes with JavaScript / jQuery?

I have almost no knowledge of JavaScript or jQuery.
I need to select/unselect an option in a <select> where multiple options can be selected when a checkbox or button is clicked.
The checkbox needs to select/unselect the option with the same value.
My idea was something like this:
$(document).ready(function() {
var input = $('#entry-select');
var checkboxes = $('.entrycheckbox');
checkboxes.click(function() {
var element = $(this);
var value = element.val();
input.val(value);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="entrycheckbox" value="1">
<input type="checkbox" class="entrycheckbox" value="2">
<input type="checkbox" class="entrycheckbox" value="3">
<form action="">
<select name="entries" id="entry-select" multiple>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
</form>
This only selects the option with the value of the last clicked checkbox, not which ones are checked, and it unselects every other option.
You only give val() the value of the checkbox which was selected last. To make this work as you require you need to build an array of all selected checkboxes and provide that to val() instead.
To achieve this you can use filter() to get the selected checkboxes, then map() to build the array:
input.val(checkboxes.filter(':checked').map((i, el) => el.value));
$(document).ready(function() {
var $input = $('#entry-select');
var $checkboxes = $('.entrycheckbox');
$checkboxes.click(function() {
$input.val($checkboxes.filter(':checked').map((i, el) => el.value));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="entrycheckbox" value="1">
<input type="checkbox" class="entrycheckbox" value="2">
<input type="checkbox" class="entrycheckbox" value="3">
<form action="">
<select name="entries" id="entry-select" multiple>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
</form>
You may also want to consider adding readonly to the select if you don't want the user to change the selected option directly.
<script type="text/javascript">
$(document).ready(function(){
$('.entrycheckbox').click(function(){
$(":entrycheckbox").each(function(){
if($(this).val()==1){
$(this).attr("checked","checked");
}
});
});
});
</script>

Get selected value of datalist option value using javascript

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>

Change the `list` attribute of an <input> in JavaScript

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

Set class from <select> if selected option contains ID='answer' in HTML/JavaScript (JQuery)

I am completely new to HTML and JQuery, and I can't figure out how I can set a class for my select element if the currently selected option has an ID="answer". I want to do this to check if the multiple choice question is correct.
If this is impossible to do this in JQuery, JavaScript would also be fine. I just want to prevent making a DataBase query and thought that JQuery would be the best route to take.
This is the current html section that I have:
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class" id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
When I click the button it runs a Javascript function called: "checkAnswers()".
This function should check if the option that is selected in the dropdown box, has an id="answer". In this case, that would be if option one is selected. And if that option is selected, I want the background color of the select element to change.
How would I go about checking the currently selected dropdown options' ID? And how do I do this for more than 1 question at a time?
And how would I add a class programaticly in JavaScript to that select element so it can change BG color?
This is what I tried in JavaScript:
var s = document.getElementsByClassName("select-class");
var idSelectedOption = s[s.selectedIndex].id;
alert(idSelectedOption);
But that returns an error: "Uncaught TypeError: Cannot read property 'id' of undefined"
I think that is because it returns an array from all classes. How would I go about checking every single one of them? And changing the background colors of the ones that have the correct option selected?
Thanks in advance,
Mats.
Use data-* attributes instead of id as you should not have multiple elements having same id value in a document.
getElementsByClassName will return nodelist hence you need to iterate through elements and then apply conditions accordingly. Array.prototype.forEach.call is used in example below to iterate through elements.
Try this:
function checkAnswers() {
var s = document.getElementsByClassName("select-class");
Array.prototype.forEach.call(s, function(elem) {
var idSelectedOption = elem[elem.selectedIndex].getAttribute('data-id');
if (idSelectedOption == 'answer') {
var selectedAnswer = elem[elem.selectedIndex].getAttribute('value');
alert(selectedAnswer);
}
});
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question</label>
<select class="form-control select-class">
<option value="1" class="ans-class" data-id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question</label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" data-id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary" onclick="checkAnswers()">Check</button>
</form>
Fiddle here
You can't have two elements with the same id. Use a custom data attribute or a class instead
After fixing that, this code should to the trick. I tried to use vanilla JavaScript since you didn't indicate using jQuery.
// Lazy: Bind the event to the form.
document.getElementById('ansForm').addEventListener('change', function(event) {
var selectElement = event.target;
// Only respond if the clicked element is one of the selects.
if (selectElement.classList.contains('select-class')) {
// Get the option that is currently selected.
var selectedOption = selectElement[selectElement.selectedIndex];
// Check if this option contains the class 'answer'.
var isAnswerSelected = selectedOption.classList.contains('answer');
console.log(isAnswerSelected);
// Remove the indicators. You could easily use classList.toggle, but the second
// argument is not supported in IE.
// selectElement.classList.toggle('right', isAnswerSelected);
// selectElement.classList.toggle('wrong', !isAnswerSelected);
// So, second best. Just remove both and re-add the class we want.
selectElement.classList.remove('right');
selectElement.classList.remove('wrong');
selectElement.classList.add(isAnswerSelected?'right':'wrong');
} else {
// Ignore clicks on any other element.
}
});
.right {
color: green;
}
.wrong {
color: red;
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
Try this for jQuery approach,
$(function(){
// This will bind 'click' event handler to element with id 'checkBtn'
$('#checkBtn').on('click', function(){
// This gets all selects element which has class containing 'select-class'.
var $selects = $('select.select-class');
// Iterate all the selects element.
$selects.each(function(k, v){
// Get the option for this current select element which has an id of 'answer'.
var $selectAnswerOpt = $(this).children('option#answer');
// Get the value attribute of the option element.
var answer = $selectAnswerOpt.attr('value');
// Get the selected value for the select element.
var selectedValue = $(this).val();
// Checking if the selected value for the select element is the option that has an id of 'answer'
if (selectedValue == answer)
{
// If the selected value has the id of 'answer'
$(this).css('background-color', 'green');
}
else
{
// Else
$(this).css('background-color', 'yellow');
}
});
});
});
And the FIDDLE

textbox values on change

I have three textboxes with the same id's in a table. I also have one dropdown on top of the table. While changing the dropdown I need to set the textbox values as same as the dropdown value.
I used the following code and I am able to change only the first textbox, others are not getting values.
function myHome() {
var zoneId = $("#funderIds").val();
$("#funder").val($("#funderIds").val());
}
<select id="funderIds" name="funderIds" onchange="myHome()" style="width: 25%;">
<option value="0">--Select--</option>
<option value="3">option1</option>
<option value="5">option2</option>
<option value="6">option3</option>
</select>
<input type="text" name="funder" id="funder" value="">
<input type="text" name="funder" id="funder" value="">
<input type="text" name="funder" id="funder" value="">
Can anyone give some advise on where I am making a mistake?
It is invalid to use same ID for more than one element, it should be unique throughout the document, thus use class instead!
ID's are unique
Each element can have only one ID
Each page can have only one element with that ID
Classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Change your code to:
function myHome() {
var zoneId = $("#funderIds").val();
$(".funder").val($("#funderIds").val());
}
<select id="funderIds" name="funderIds" onchange="myHome()" style="width:25%;">
<option value="0">--Select--</option>
<option value="3">option1</option>
<option value="5">option2</option>
<option value="6">option3</option>
</select>
<input type="text" name="funder-1" id="funder-1" class="funder" value="">
<input type="text" name="funder-2" id="funder-2" class="funder" value="">
<input type="text" name="funder-3" id="funder-3" class="funder" value="">
Id has to be unique, try name instead with min changes:
function myHome() {
var zoneId = $("#funderIds").val();
$("input[name=funder]").val(zoneId);
}
Edited:
To get option text, use :selected:
function myHome() {
var zoneId = $("#funderIds option:selected").text();
$("input[name=funder]").val(zoneId);
}
IDs are unique identifier,they should always be unique. If you have multiple elements with same ID, ID selector ($(".funder") in your case) will return the object of first element only.
You can rather use same class and use class selector to target all the element.
HTML:
<input type="text" name="funder" class="funder" value="">
<input type="text" name="funder" class="funder" value="">
<input type="text" name="funder" class="funder" value="">
JS:
function myHome() {
var zoneId = $("#funderIds").val();
$(".funder").val(zoneId );
}
function myHome() {
var zoneId = $("#funderIds").val();
$(".funder").val(zoneId);
}
<select id="funderIds" name="funderIds" onchange="myHome()" style="width:25%;">
<option value="0">--Select--</option>
<option value="3">option1</option>
<option value="5">option2</option>
<option value="6">option3</option>

Categories