jQuery select option last doesn't work - javascript

I've got a button and list of options. The idea is that when user clicks the button the default option changes from disabled to max value. And oposite - if the input is not checked, the default is again disabled.
But the value returns undefined. If I change the first and thelast to numeric values, everything works fine. What's wrong?
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected> -- choose -- </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
jQuery(function(){
jQuery(".input").click(function(){
var thefirst = jQuery(this).next('#select option:first').val();
var thelast = jQuery(this).next('#select option:last').val();
if( jQuery(this).is(':checked') )
jQuery(this).next('#select').val(thelast);
else
jQuery(this).next('#select').val(thefirst);
});
});

.next() gets the next sibling, so you need to get the select and use .find() or .children() afterwards:
var thefirst = jQuery(this).next('#select').find('option:first').val();
var thelast = jQuery(this).next('#select').find('option:last').val();

Since IDs must be unique, there's no point in doing something like:
jQuery(this).next('#select option:first')
when
jQuery('#select option:first')
would suffice, plus .next() would fail here since it evaluates the siblings of an element and filters on anything you pass, but your filter is what would cause it to not match anything.
Instead, use:
jQuery(".input").click(function () {
var thefirst = jQuery('#select option:first').val();
var thelast = jQuery('#select option:last').val();
if (jQuery(this).is(':checked')) jQuery('#select').val(thelast);
else jQuery('#select').val(thefirst);
});
jsFiddle example

The vanilla javascript alternative for future viewers
(function () {
"use strict";
var inputs = document.getElementsByClassName('input'), input;
for (var i = 0; input = inputs[i]; i++) {
input.addEventListener('click', function (e) {
e.target.nextElementSibling.lastElementChild.selected = e.target.checked;
e.target.nextElementSibling.firstElementChild.selected = !e.target.checked;
}, false);
}
})();
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected>-- choose --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>

Related

Clicking on the first option js

Tell me please, there is a code in which when you click option select, a div element is added with an option value.
But there is a problem, which is that you cannot immediately click on the first option, you must first click on the second, and only after the first. How to fix this problem?
Thank you in advance.
var p = document.getElementById("inputi");
var length = 1;
function add_input_from_select(select) {
var new_input = document.createElement("input");
new_input.name = "my_input";
new_input.value = select.value;
var div = document.createElement('div');
div.innerHTML = '<br>div элемент №' + length + '<br>';
div.appendChild(new_input);
p.appendChild(div);
length++;
}
function add_input_old() {
add_input_from_select(document.getElementById("selector"));
}
<select id="selector" onchange="add_input_from_select(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<form>
<div id="inputi"><input name="my_input"></div>
</form>
In html dropdown you can not able to select a value which already selected, so must need to add one more option in your dropdown which say "Please Select" and after that you can able to select any option. That's the right solution
See working example:-
var p = document.getElementById("inputi");
var length = 1;
function add_input_from_select(select) {
var new_input = document.createElement("input");
new_input.name = "my_input";
new_input.value = select.value;
if(!new_input.value) return false;
var div = document.createElement('div');
div.innerHTML = '<br>div элемент №' + length + '<br>';
div.appendChild(new_input);
p.appendChild(div);
length++;
}
function add_input_old() {
add_input_from_select(document.getElementById("selector"));
}
<select id="selector" onchange="add_input_from_select(this)">
<option value="">Please Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<form>
<div id="inputi"><input name="my_input"></div>
</form>
This happens because you done it with onchange event so the first option is already selected thats why first time it doesn't add div so for overcome that just add one more option to html like
<select id="selector" onchange="add_input_from_select(this)">
<option value="">select Option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
and put condition in javascript like,
if(document.getElementById("selector").value != ""){
//add your div here
}
this condition must apply because when you select first option it did not be added like select options.

how to preserve all select elements selected values in jquery

Can you help me to solve this problem.
The problem is this.
I have multiple select lists with same class name but different ids. If user select same option which is already selected in other select list then there should be an alert. and after alert the current select list which is clicked or changed should be restore to the previous value. for example we have 3 select boxes name as A1, A2, A3. Each one have same values for example 1,2,3,4. A1 selected value is 1, A2 selected value is 2 and A3 selected value is 3. Now if your want to change A1 value from 1 to 2 then there should be an alert like "Already selected". After this alert A1 list should be restored back to its original value which is 1. I tried the following code. In this code I can get already existing alert but the value of the last changes select box is changed to new one.
$(document).ready(function(){
var init = true;
if(init == true){
var a = new Array();
$(".brand-list").each(function(i, obj){
var current_obj_id = $(this).attr('id');
var current_obj_value = $('#'+ current_obj_id + " option:selected").val();
a[current_obj_id] = current_obj_value;
});
init = false;
}
$(".brand-list").change(function(){
a[$(this).attr('id')] = $('#'+ $(this).attr('id') + " option:selected").val();
var current_selected_obj_id = $(this).attr('id');
var current_selected_obj_value = $('#'+ $(this).attr('id') + " option:selected").val();
$(".brand-list").each(function(i, obj){
var current_obj_id = $(this).attr('id');
var current_obj_value = $('#'+ current_obj_id + " option:selected").val();
if(current_obj_id != current_selected_obj_id){
if(current_selected_obj_value == current_obj_value){
alert("current element global value: "+ a[current_selected_obj_id]);
$('#'+ current_selected_obj_id + " option[value=" + a[current_selected_obj_id] +"]").attr('selected','selected')
alert("already selected");
}
}else{
a[current_obj_id] = current_obj_value;
}
});
});
$( ".brand-list" ).focus(function() {
var current_selected_obj_id = $(this).attr('id');
var current_selected_obj_value = $('#'+ $(this).attr('id') + " option:selected").val();
a[current_selected_obj_id] = current_selected_obj_value;
console.log(a[current_selected_obj_id]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="inputBrand-1" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-2" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-3" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
</select>
Hopefully you can understand my question, because I'm not get to ask question which community members can understand easily. Thanks
You can save the previous value and check it then
$(document).ready(function(){
var init = true;
if(init == true){
var a = new Array();
$(".brand-list").each(function(i, obj){
var current_obj_id = $(this).attr('id');
var current_obj_value = $('#'+ current_obj_id + " option:selected").val();
a[current_obj_id] = current_obj_value;
});
init = false;
}
function hasConflict(input){
var conflict = false;
$(".brand-list").not(input).each(function(i, obj){
if($(this).val()==input.val()){
conflict = true;
return false; //break the loop
}
});
return conflict;
}
$(".brand-list").change(function(){
var $this = $(this); //recycle object
if(hasConflict($this)){
$this.val($this.data('prev'));
alert("Conflict"); //do whatever
}
});
$( ".brand-list" ).on('click focus',function() {
$(this).data('prev',$(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="inputBrand-1" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-2" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-3" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
</select>
Rather than annoy user by letting them select something and be told they can't it's better UX to either disable previous selections or remove them completely.
Here's an approach that manages the filtering/removing of other selections
var $selects = $(".brand-list"),
// store a cloned set of all options
$storedOptions = $selects.first().children().clone().removeAttr('selected'),
// whether to always include "SELECT A BRAND"
alwaysShowDefault = true;
$selects.change(function() {
// create array of all the selected values
var allValues = $selects.map(function() {
return $(this).val()
}).get();
// loop through each select to create filtered options
$selects.each(function(i) {
// new set of cloned and filtered options for this select instance
var $opts = $storedOptions.clone().filter(function() {
if(+this.value === -1){
return alwaysShowDefault || +allValues[i] === -1;
}
return allValues[i] === this.value || allValues.indexOf(this.value) === -1;
});
// update filtered options and reset current value
$(this).html($opts).val(allValues[i])
})
// trigger one change on page load to filter what is already selected
}).first().change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="inputBrand-1" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-2" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-3" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" >3</option>
<option value="4">4</option>
</select>
Actually you'r currently doing is manually setting the selected attribute on each option element. It is not a good approach because it doesn't remove other attributes of options of the same select element. So use following code in your source.
$(e.currentTarget).val(-1);
Replace following code with above one
$('#'+ current_selected_obj_id + " option[value=" + a[current_selected_obj_id] +"]").attr('selected','selected')

Select has an empty value

I`ve a "select":
<select class="date-select2" name="date">
<option selected="selected" value="">All</option>
<option value="11-2015">11-2015</option>
<option value="10-2015">10-2015</option>
<option value="09-2015">09-2015</option>
<option value="07-2015">07-2015</option>
<option value="06-2015">06-2015</option>
<option value="04-2015">04-2015</option>
<option value="03-2015">03-2015</option>
</select>
When I`m try to get value of select,
document.getElementsByClassName('date-select2')[0].value
it normally returns a value of selected item in Chrome. In FF and Safari sometimes it returns an empty string, when selected a numeric value(not "All").
How to deal with it?
I think this might help you:
HTML
<select class="date-select2" name="date" onchange="myFunction(this.value)">
<option selected="selected" value="">All</option>
<option value="11-2015">11-2015</option>
<option value="10-2015">10-2015</option>
<option value="09-2015">09-2015</option>
<option value="07-2015">07-2015</option>
<option value="06-2015">06-2015</option>
<option value="04-2015">04-2015</option>
<option value="03-2015">03-2015</option>
</select>
JavaScript
function myFunction(curValue) {
alert(curValue);
}
Working : Fiddle
Note: Also remember to put your JavaScript code inside body also right before it ends.
var select = document.querySelector('select.date-select2');
// add onchange handler
select.onchange = function(){
var idx = select.selectedIndex;
var val = select.options[idx].value;
// if All is selected use text of option
if(val=="")
val = select.options[idx].textContent;
};
You can try this way to get selected item:
$(".date-select2 option:selected").text();

Mandatory fields and selecting drop down list values

Basically, I have two fields, one a selection (drop down) list and the other an input textbox, both different question's.
My question is, if I choose only one value in the selection list (first question), the textbox (second question) must be 6 characters or numbers in length. Otherwise, the other values chosen in the selection list can be 10 characters long in the textbox.
How can I write this in Javascript form without the use of regex and within ?
I have written parts of this script but I would like to see how others can write it. My sole problem is to get the rest of the other values to be 10 characters long.
I'd also like to add that the first question does not need to be a selection list. I made it this way for the html to be more presentable and organised.
This is my script (so far):
function imposeMaxLength(object, limit) {
var num = document.getElementById("Number").value;
if (num == "3") {
document.getElementById("Type").value {
return (object.value.length <= limit);
}
}
}
HTML:
<label for="number">Number:</label>
<select size="1" id="Number">
<option disabled>...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br>Type:<input type="text" id="Type" onkeypress="return imposeMaxLength(this,6);"><br>
<input type="button" value="submit"/>
Please help.
i think you need this
<script>
$('#Number').on('change', function () {
var value=this.value;
if(value==1)
{
$("#Type").attr('maxlength','6');
}
else
{
$("#Type").attr('maxlength','10');
}
});
</script>
This sets the maxlength to the required value whenever the Select element changes. So if you do select multiple values, then the maxlength will change to 10, otherwise, if only 1 item is selected it will have a maxlength of 6.
<div>
<select size="1" id="Number" multiple>
<option disabled>...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div>
<input type="text" id="Type" />
</div>
<div>
<input type="button" value="submit"/>
$("#Number").on('change', function() {
var selects = $(this).find('option:selected');
if(selects.length > 1) {
$("#Type").attr('maxlength', 10);
} else {
$("#Type").attr('maxlength', 6);
}
});
Demo
u may simply use the property maxlength:
html
<input type="text" id="Type" maxlength="1"/><!-- default value in select -->
<select onchange="imposeMaxLength(this.value);">
js
<script>
function imposeMaxLength(max) {
document.getElementById("Type").maxlength = max;
}
</script>

jQuery/ Javascript change select options based on selected answer

I have the following code:
<table>
<tr><td>Item</td><td>Ranking</td></tr>
<tr><td>Apples</td><td><select id="apple" name="apple">
<option value="#" selected="selected">Rank...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td></tr>
<tr><td>Oranges</td><td><select id="oranges" name="oranges">
<option value="#" selected="selected">Rank...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td></tr>
<tr><td>Bananas</td><td><select id="bananas" name="bananas">
<option value="#" selected="selected">Rank...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td></tr>
<tr><td>Lemons</td><td><select id="lemons" name="lemons">
<option value="#" selected="selected">Rank...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td></tr>
<tr><td>Limes</td><td><select id="limes" name="limes">
<option value="#" selected="selected">Rank...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td></tr>
<tr><td>Kiwi</td><td><select id="kiwi" name="kiwi">
<option value="#" selected="selected">Rank...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td></tr>
And here in jsFiddle: http://jsfiddle.net/XNYU2/
I'm trying to understand if this is possible and, if so, whether jQuery or Javascript is the best solution and how I'd go about making it happen.
It's a ranking system and what I need to happen is simple. If a user selects from any dropdown any value, that value needs to be removed from the other dropdowns. Conversely, if the user then unselects that value, it needs to return to all the dropdowns.
Try this:
$(function() {
$('select').on('change', function(event){ // This binds listeners to the change event on all the select elements
var sId = this.id; // store off the changed element id
var vId = this.value; // store off the changed element value
$('select').each( function(){ // this loops across the same set of elements
if(this.id != sId && this.value == vId) { // If it is not the triggering element and the value is the same, do something
this.options.selectedIndex = 0; // reset the value to 'rank'
}
});
});
});
You can do this in either jQuery or pure js, but jQuery selectors sure make it easy to loop through the elements and apply actions on change with very little code.
Upon re-reading you question, this accomplishes the same thing but slightly differently; the user is forced to have only 1 set of ordered ranking with no overlap, but we don't have to go to the trouble of removing/adding options.
Yes, this is a task for JavaScript. jQuery isn't an alternative to JavaScript but basically a toolset on top of it that makes manipulation of browser elements easier. I recommend using it, even though you'll need to understand JavaScript basics in order to use it effectively.
The key here is to decompose your problem; one is to perform an action once a Select has been changed. See here how this is done: http://api.jquery.com/change/
The second action is to actually implement the change, which is described e.g. here
Removing an item from a select box
The jsFiddle is here and that's the code:
var SelectOptions = ['Rank...', 1, 2, 3, 4, 5];
$(document).ready(function () {
$('#TheTable').find('select').change(function () {
var TheSelectedValue = parseInt($(this).val(), 10);
var TheSelectID = $(this).prop('id');
var TheHTML = "";
for (var i = 0; i < SelectOptions.length; i++) {
if (SelectOptions[i] !== TheSelectedValue) {
TheHTML = TheHTML + '<option value="';
TheHTML = (i === 0) ? TheHTML + '#' : TheHTML + SelectOptions[i];
TheHTML = TheHTML + '">' + SelectOptions[i] + '</option>';
}
}
$('#TheTable').find('select').each(function () {
if ($(this).prop('id') !== TheSelectID) {
$(this).html(TheHTML);
}
});
});
});
That's just one way to do it: I put it together in a few minutes and I'm sure it can be improved but that should get you started.

Categories