I have a simple form with some options in it which are disabled and greyed out by default.
<select name="template" id="template" size="1" >
<option disabled selected value="1" name="1" id="1" class="bold-option">Mango</option>
<option class="select1"></option>
<option disabled selected value="2" class="bold-option" >Apple</option>
<option disabled selected value="3" class="bold-option">Pineapple</option>
<option disabled selected value="4" class="bold-option">Brocolli</option>
<option disabled selected value="5" class="bold-option">Peach</option>
<option disabled selected value="6" class="bold-option">Strawberry</option>
</select>
The idea behind it is that i want multiple variables which are defined by JQuery are getting imported into the select1 option for example, so the items that are linked to Select1 are listed below Mango.
I've made a var :
var issueTemplates = [
{'subject': 'This is a mango'}
];
Now i want to add this variable into the Option value beneath (or linked) to the Mango option within the select. I've looked into the append function but i cant seem to figure out how to get this straight.
I've made a select request in jquery which adds the subject in the dropdown form. But i want to have it beneath the Mango option..
This is de code
issueTemplates.forEach(function(item, idx) {
$("select[id='template']").append('<option value="' + idx + '">' + item.subject + '</option>');
This will get you started. If you have an array of additional options, you can iterate through the select element and load by index -1.
$(document).ready(function() {
var fruit = ['mango', 'apple', 'pineapple', 'brocolli', 'peach', 'strawberry']
$('#template option').each(function() {
val = $(this).val();
$(this).after('<Option val = ' + val + '>This is a ' + fruit[val - 1] + '</option>');
});
console.log($('#template option'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="template" id="template" size="1">
<option disabled selected value="1" name="1" id="1" class="bold-option">Mango</option>
<option disabled selected value="2" class="bold-option">Apple</option>
<option disabled selected value="3" class="bold-option">Pineapple</option>
<option disabled selected value="4" class="bold-option">Brocolli</option>
<option disabled selected value="5" class="bold-option">Peach</option>
<option disabled selected value="6" class="bold-option">Strawberry</option>
</select>
Related
Field 1 [attribute_size]
Drop down menu
Values: Small, Medium, Large, Extra Large
Field 2 [count]
Input text
Value: Set value depending on Field 1 input based on the following mappings
Small = 1
Medium = 2
Large = 3
Extra Large = 4
<select id="size" class="" name="attribute_size" data-
attribute_name="attribute_size" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="Small" class="attached enabled">Small</option>
<option value="Medium" class="attached enabled">Medium</option>
<option value="Large" class="attached enabled">Large</option>
<option value="Extra Large" class="attached enabled">Extra
Large</option></select>
<input id="count" name="count" value="5" class="thwepo-input-field ">
How could I achieve this using JQuery? I need the value of Field 2 to update every time Field 1 is changed.
const input = document.getElementById('count');
document.getElementById('attribute_size').addEventListener('change', function(){
var sizsel = document.getElementById('attribute.size').value;
if (sizsel = 'Small') {
input.value = '5';
} else if (sizsel = 'Medium') {
input.value = '10';
} else {
input.value = "15";
}
});
You would set up a change event handler on the select that sets the value of the input:
const $input = $("#size");
$input.change(function(){
$("#count").val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="size" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="1" class="attached enabled">Small</option>
<option value="2" class="attached enabled">Medium</option>
<option value="3" class="attached enabled">Large</option>
<option value="4" class="attached enabled">Extra Large</option>
</select>
<input id="count" name="count" value="5" class="thwepo-input-field ">
But, a couple of things about this:
An input field is just that, an element for user input. If you just
need to display information, you should not be using an input
element, but rather you should just set the textContent of a normal
element (like a span or div).
If you want the value of an option to be the same thing as the
text of the option, you don't need to specify the value attribute
of the option at all - - the text will become the value. But, in your case, you've said that you want numbers to be the values of the different options, so the value attribute should reflect that.
The scenario you've asked about is extremely simple and JQuery is
probably overkill to accomplish it. Here's what the code would be
with vanilla JavaScript:
const input = document.getElementById("count");
document.getElementById("size").addEventListener("change", function(){
input.value = this.value;
});
<select id="size" class="" name="attribute_size" data-attribute_name="attribute_size" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="1" class="attached enabled">Small</option>
<option value="2" class="attached enabled">Medium</option>
<option value="3" class="attached enabled">Large</option>
<option value="4" class="attached enabled">Extra Large</option>
</select>
<input id="count" name="count" value="5" class="thwepo-input-field ">
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>
How can i display the options from select-option tag with different button
I have a div or maybe another button. From this button i need to view the list of option from my select tag
my select tag is:
<select>
<option value="0" selected="selected">Choose a class...</option>
<option value="1" >2</option>
<option value="2" >3</option>
<option value="3" >4</option>
</select>
and then my another button from where if i click this button i should see the list of above option (at above location)
<button>My button</button>
Seems that there is no way to open the select like default select open action.
But there's another way that may meet your requirement.
Here is an example to open select options by changing the size attribute.
var select = document.getElementsByTagName('select')[0];
var button = document.getElementsByTagName('button')[0];
button.addEventListener("click", function(){
var size = select.getAttribute("size");
if(size == null || size == 0){
// you can determine the height of opening select
select.setAttribute("size", 5);
}
else{
select.setAttribute("size", 0);
}
}, false);
select.addEventListener("change", function(){
this.setAttribute("size", 0);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">Choose a class...</option>
<option value="1" >2</option>
<option value="2" >3</option>
<option value="3" >4</option>
</select>
<button>My button</button>
Im trying to get value from checkbox that has been checked, but for some reason the value is shuffled in some weird pattern
here jsfiddle (try to check fruit and then click disable)
<input id="checkedTree" type="text"/>
<select id="test-select" onchange="getCheckedTree()">
<option value="1" data-section="fruit">Banana</option>
<option value="2" data-section="fruit">Apple</option>
<option value="3" data-section="fruit">Avocado</option>
<option value="4" data-section="fruit">Pineapple</option>
<option value="5" data-section="fruit">PenPineappleApplePen</option>
<option value="6" data-section="animal">Tiger</option>
<option value="7" data-section="animal">Lion</option>
<option value="8" data-section="animal">Pitbull</option>
<option value="9" data-section="animal">OrangUtan</option>
<option value="10" data-section="animal">Marsupilami Yellow cartoon</option>
</select>
I need to know why is it happened, and how to fix it. i do know the other way to get proper value like this. But for my project case i need "for" method
Update 1-> update jsfiddle
Values shuffled because you are getting the input array index checkedText.value = selectobject[z].value; knowing that at the change event the order of your hidden inputs change which causes the wrong values . (you can check by setting test-select display :block after page loding )
Above a working snippet :
note that you can passe directly value (1,2,3.. ) to the checkedTree input to disable directly inputs .
$( document ).ready(function() {
var $select = $('#test-select');
$select.treeMultiselect({
enableSelectAll: true,
sortable: false,
searchable: true,
startCollapse: true
});
});
function getCheckedTree(){
var tempCtr=0;
var $checkedText = $("#checkedTree");
var selectobject = $("[id*=treemultiselect-0-]:checked");
$checkedText.val("");
for(i=0;i<selectobject.length;i++) {
if(tempCtr==0){
tempCtr=1;
$checkedText.val($(selectobject[i]).parent().data("value"));
}else{
$checkedText.val($checkedText.val() + $(selectobject[i]).parent().data("value"));
}
}
}
function funcDis(){
var $checkedText = $("#checkedTree");
if($checkedText.val().length>0) {
$checkedText.val().split("").forEach(function(val){
$(".tree-multiselect .item[data-value="+val+"] input").prop('disabled', true);
$("#test-select option[value="+val+"]").prop('disabled', true);
})
};
}
function enableAll(){
$(".tree-multiselect input").each(function(idx){
$(this).prop('disabled', false);
var val = $(this).parent().data("value");
$("#test-select option[value="+val+"]").prop('disabled', false);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link href="//cdn.rawgit.com/patosai/tree-multiselect/v2.1.3/dist/jquery.tree-multiselect.min.css" rel="stylesheet"/>
<script src="//cdn.rawgit.com/patosai/tree-multiselect/v2.1.3/dist/jquery.tree-multiselect.min.js"></script>
<input id="checkedTree" type="text"/> <button onclick="funcDis()">disable</button><button onclick="enableAll()">enable all</button>
<select id="test-select" onchange="getCheckedTree()">
<option value="1" data-section="fruit">Banana</option>
<option value="2" data-section="fruit">Apple</option>
<option value="3" data-section="fruit">Avocado</option>
<option value="4" data-section="fruit">Pineapple</option>
<option value="5" data-section="fruit">PenPineappleApplePen</option>
<option value="6" data-section="animal">Tiger</option>
<option value="7" data-section="animal">Lion</option>
<option value="8" data-section="animal">Pitbull</option>
<option value="9" data-section="animal">OrangUtan</option>
<option value="10" data-section="animal">Marsupilami Yellow cartoon</option>
</select>
PS:You can pass dirctly an array of value to funcDis and disable input at start up .
That's all ,I fiddle if you want.
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