Clicking on the first option js - javascript

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.

Related

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

FadeIn fadeOut depending upon the previous option value in select [duplicate]

I have 4 Drop Downs.
Each drop by default has a --select-- option. Each box has a unique id. As you can see, the second drop down is disabled if the above drop down value is --select--. It will only enable when the value is anything but --select--
Here's my code:
$(document).ready(function() {
$('#idOfTheFirstDropDown').bind('change', function() {
var options = $(this).children('option');
var item = $('div.c-select').children().hide(); // hide all the elements
var value = Math.floor(Math.random() * options.length );
//console.log(value);
if (value.length) { // if selected
item.show(); // show the next dropdown
}
}).trigger('change');
});
I want it to show the next dropdown only when my previous drop down value is not --select--. My code is taking in the first drop down but not changing the value. What am I doing wrong? Thanks.
My HTML for one drop down box. Only the ID's change for the remaining 3. Rest of the HTML remains the same.
<div class="c-select">
<select name="list1" onchange="javascript:setTimeout('__doPostBack(\'list1\',\'\')', 0)" id="idOfTheFirstDropDown" class="GroupDD dropDown ">
<option selected="selected" value="">-- Select --</option>
<option value="1">Group1</option>
</select>
</div>
Rather than hiding the options, I would use the disable attribute (comments in code):
var selects = $('.drop-down');
selects.not(':eq(0)').prop('disabled', true); // disable all but first drop down
selects.on('change', function() {
var select = $(this),
currentIndex = selects.index(select),
nextIndex = currentIndex + 1;
// only do this if it is not last select
if (currentIndex != selects.length - 1) {
selects.slice(nextIndex) // get all selects after current one
.val('') // reset value
.prop('disabled', true); // disable
selects.eq(nextIndex).prop('disabled', select.val() === ''); // disable / enable next select based on val
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<select class="drop-down">
<option value="">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Check this one;
HTML code:
<select id="sel-1"></select>
<select id="sel-2"></select>
<select id="sel-3"></select>
<select id="sel-4"></select>
JS Code:
$(document).ready(function(){
$("[id^=sel]").change(function(){
/*
* find out the current box id
*/
var id=$(this).attr("id");
/*
* find out the current box id order number
*/
var ordernumber=id.split("-")[1];
if($(this).val()!="select")
{
//enable next one
$("#sel-"+(ordernumber+1)).show();
}
})
})
Assuming the option that has '--select--' as text has no value, just use val on the handler to check if the selected option is other than the empty
if(this.val() !== '') {
// enable following select
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
select {
margin: 5px 0;
display: block;
}
</style>
<script>
$(function() {
$('.cls-select').change(function() {
if ($(this).val() == '--select--') {
// reset and disable the next drop downs
$('.cls-select:gt(' + $('.cls-select').index($(this)) + ')').val('--select--').prop('disabled', true)
} else {
// current drop down has value so enable the next drop down
$(this).next().prop('disabled', false);
}
});
})
</script>
<select class="cls-select">
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>
<select class="cls-select" disabled>
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>
<select class="cls-select" disabled>
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>
<select class="cls-select" disabled>
<option>--select--</option>
<option>one</option>
<option>two</option>
</select>

jQuery select option last doesn't work

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>

Create div based on selected drop down value

I want to create one or more div dynamically based on selected values in dropdown.
HTML code:
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="10">10</option>
</select>
If I select 2 from the dropdown means, two div will create, if I select 10 means 10 div will create. How can I do this?
$('select').on('change', function() {
$('#result').empty();
$.each(new Array(+this.value), function(i) {
$('<div />', {
text : 'this is div nr : '+(i+1)
}).appendTo('#result');
});
});
FIDDLE
Simple :)
var val,html = $('samplediv').clone().html(); //store the html to be appended in a sample div
$('select').change(
val = $(this).val();
for(i=0;i<val;i++)
{
$(this).after(html);
}
);
Try this
HTML
<select><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="10">10</option></select>
<span id="test">
//Here your Dynamic Divs Whenver Select Changes
</span>
Script
$('select').on('change',function(){
var value=$(this).val();
var output='';
for(var i=1;i<=value;i++)
{
output+='<div>Your Text</div>'
}
$('#test').empty().append(output);
});
DEMO
try this
HTML
<select onchange="javascript:create_div(this.value);" id="my_select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="10">10</option>
</select>
<div id="div_main"></div>
add onchange funciton in select and a div_main in which you want to insert divs
JS Script
<script>
function create_div(num)
{
alert("hi");
alert(num);
var html = "";
for(var i=1; i<=num; i++)
{
html += '<div id="div'+i+'">This is Div No - '+i+'</div>';
}
document.getElementById('div_main').innerHTML = html;
}
</script>
use above js script to create dynamic div
See JS Fiddle

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