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

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>

Related

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

Disable select box and enable textbox using one checkbox with JavaScript

I'm am fairly new to JavaScript; I have been googling all day for this but i only found how to enable and disable one textbox using one checkbox.
Here is my code
JavaScript
function enable_text(status){
status=!status;
document.sr2.other_text.disabled = status;
}
HTML
<form name=sr2 method=post>
<input type="checkbox" name=others onclick="enable_text(this.checked)">
Others
<input type=text name=other_text>
</form>
Note: the code I posted is only for a textbox that when uncheck in checkbox it will be enabled.
My question is how do you disable select tag and enable a textbox after unchecking a checkbox?
Add an id to your text box then just put the below onclick of your checkbox instead of the function call.
<form name=sr2 method=post>
<input type="checkbox" name=others onclick= "document.getElementById('id_of_txtbox').disabled=this.checked;">Others
<input type=text name=other_text>
Here's the HTML
<input type="text" id="txt" disabled="disabled"/>
<select name="sel" id="sel">
<option value="test1">Test 1</option>
</select>
<input type="checkbox" name="vehicle" value="Car" checked="checked" onclick="enableText(this.checked)">Uncheck to Disable Select and Enable Text
And the JavaScript is
function enableText(checked){
if(!checked){
document.getElementById('sel').disabled = true;
document.getElementById('txt').disabled = false;
}
else{
document.getElementById('sel').disabled = false;
document.getElementById('txt').disabled = true;
}
}
Select is disabled and text is enabled on uncheking the checkbox and vice versa. Hopefully that helps.
Based on your question, are you trying to present a dropdown but then allow them to enter other values not in the dropdown?
If so, here is another way to approach it:
HTML:
<select name="RenewalTerm" id="RenewalTerm">
<option value="12">12 Month</option>
<option value="24">24 Month</option>
<option value="36">36 Month</option>
<option value="Other">Other</option>
</select>
<span id="RenewalTermOtherFields">
<label labelfor="RenewalTermManual" >Enter Renewal Term: </label>
<input type="text" name="RenewalTermManual" id="RenewalTermManual" />
</span>
JavaScript/jQuery:
$(document).ready(function() {
$('#RenewalTermOtherFields').hide();
$('#RenewalTermManual').val($('#RenewalTerm').val());
$('#RenewalTerm').change(function() {
var selectedItem = $("select option:selected").val();
if (selectedItem !== 'Other') {
$('#RenewalTermOtherFields').hide();
$('#RenewalTermManual').val($('#RenewalTerm').val());
}
else
{
$('#RenewalTermManual').val('');
$('#RenewalTermOtherFields').show();
}
});
});
See It In Action!: http://eat-sleep-code.com/#/javascript/dropdown-with-other-field
This will allow you to select "other" from the list, and when you do it will automatically display a textbox for free-form entry.

jQuery set dropdown value on checkbox change

I have a group of dynamic rows each with a dropdown and checkboxes and need to change the individual dropdown value of that row if all its checkboxes are selected.
Currently I can only get this to work if I select all checkboxes in all rows.
How can I make it so only a row's dropdown changes when the checkboxes it belongs to are all selected?
I setup this fiddle with markup of what works right now. Thanks for the help!
http://jsfiddle.net/uyv3mk7b/
<!--First row eventRegistrations[1]-->
<select class="regSelect" name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14 <br>
<!--There could be multiple dynamic rows whose input names increment like eventRegistrations[i]-->
<!--Next dynamic row eventRegistrations[2]-->
<select class="regSelect" name="eventRegistrations[2].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[1].attendanceDate" value="1">10/23/14
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[2].attendanceDate" value="2">10/24/14
//Change dropdown to Attended when all of checkbox group is selected
//Currently only works when all 4 checkboxes are selected, not the 2 in each group/row
$('.regChecked:checked').length == $('.regChecked').length
$(".regChecked").change(function () {
if ($('.regChecked:checked').length == $('.regChecked').length) {
$('.regSelect').val('2');
}
});
You need to add a wrapper to your rows, like section, or div, and on change, you can loop through only the parents childrens collection.
Tyr this: http://jsfiddle.net/uyv3mk7b/3/
HTML
<!--First row eventRegistrations[1]-->
<section>
<select class="regSelect" name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect1">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" class="regChecked" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14 <br>
</section>
<!--There could be multiple dynamic rows whose input names increment like eventRegistrations[i]-->
<!--Next dynamic row eventRegistrations[2]-->
<section>
<select class="regSelect" name="eventRegistrations[2].eventRegistrationStatusTypeID" id="registrationStatusSelect2">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[1].attendanceDate" value="1">10/23/14
<input type="checkbox" class="regChecked" name="eventRegistrations[2].markAttendance[2].attendanceDate" value="2">10/24/14
</section>
jQuery
//Change dropdown to Attended when all of checkbox group is selected
$(".regChecked").change(function() {
var checks = $(this).parent().find('.regChecked');
var allChecked = true;
$.each(checks, function(idx, value) {
if (!$(this).is(':checked')) {
allChecked = false;
}
});
if (allChecked) {
$(this).parent().find('.regSelect').val(2);
} else {
$(this).parent().find('.regSelect').val(1);
}
});
//When dropdown value is Attended, select all in checkbox group
$("select").change(function() {
if ($(this).val() === '2') {
$(this).parent().find('.regChecked').prop('checked', true);
}
});
You can add some sort of identifier to each group like
<select class="regSelect group-select-1" name="eventRegistrations[1].eventRegistrationStatusTypeID" id="registrationStatusSelect">
<option value="1">Pending</option>
<option value="2">Attended</option>
</select>
<input type="checkbox" class="regChecked group-1" name="eventRegistrations[1].markAttendance[1].attendanceDate" value="1">9/21/14
<input type="checkbox" class="regChecked group-1" name="eventRegistrations[1].markAttendance[2].attendanceDate" value="2">9/22/14 <br>
and then manipulate with this identifiers
$(".group-1").change(function () {
if ($('.group-1:checked').length == $('.group-1').length) {
$('.group-select-1').val('2');
}
});
Fiddle
UPD Added fiddle with else cases, thx to Roberto Linares.
P.S. ids have to be unique

Change radio by Id attr to checked on select change

Trying to set the radio inputs attribute to checked on select change.
Select HTML
<select onChange="jsFunction()" name="templateId" id="selectOpt" required="required">
<option value=""></option>
<option onclick="jsFunction()" value="slides_1">subject1</option>
<option onclick="jsFunction()" value="slides_2">subject2</option>
<option onclick="jsFunction()" value="slides_2">subject2</option>
</select>
jQuery
<script>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
var mySlide = myselect.options[myselect.selectedIndex].value;
document.getElementById.mySlide.prop('checked', 'checked');
}
</script>
Radio HTML
<input type="radio" name="slides" check="checked" id="slides_1"/>
<input type="radio" name="slides" id="slides_2"/>
<input type="radio" name="slides" id="slides_3"/>
Thanks -Hector
For JS, see the function below.
For the HTML part, remove the onclick="jsFunction()" field on the options, and changed the last option to "slides_3".
See the working code at:
JSFiddle
JS:
function jsFunction() {
var selectedID = $('select#selectOpt').val();
$('input[type=radio]').filter('#'+selectedID).prop('checked', true);
}
HTML(updated):
<select onChange="jsFunction()" name="templateId" id="selectOpt" required="required">
<option value=""></option>
<option value="slides_1">subject1</option>
<option value="slides_2">subject2</option>
<option value="slides_3">subject3</option>
</select>
<div>
<input type="radio" name="slides" checked="checked" id="slides_1"/>
<input type="radio" name="slides" id="slides_2"/>
<input type="radio" name="slides" id="slides_3"/>
</div>
Import jquery:
<script type="text/javascript" src="you_jquery_file"></script>
You can download here: http://jquery.com/download/
Then change:
document.getElementById.mySlide.prop('checked', 'checked');
to:
$("#"+mySlide).prop('checked', 'checked');
For this particular problem, you don't need jQuery. Something like this will do:
function checkRadio(name, id) {
var rGroup = document.getElementsByName(name);
var theRadio = document.getElementById(id);
// uncheck the checked ones
for (var i=0;i<rGroup.length;i++) {
rGroup[i].checked = false;
}
// check the appropriate button
theRadio.checked = true;
}
// bind custom event to your select list
var mylist = document.getElementById('some_select_list');
mylist.addEventListener('change', function() {
var selected = this.options[this.selectedIndex].value;
checkRadio('radio_group_name', selected);
}, false);

Use created attribute with javascript in select list

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

Categories