How to update select options before showing them in Jquery? - javascript

Look at this example code:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").on('click', "#teste",function(){
$('#teste').append('<option id="pera">pera</option>')
$('#teste').show();
});
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>
My problem here is that the click event show the select box and only after it updates it with the new value ("pera"). What I need to do is first update the select with the new value and only after show it. Is there anyway to do that using jQuery? Thanks in advance, guys!
EDIT:
Ok, let me try to explain a little bit clear: Whenever you click in a select to show the options it show it automatically (it's obvious!). My problem is that I need to intercept the click event, update the select and only after it show the select. But it's showing the select (it's the default behaviour) before updating. Here is what happening:
1) Select with initial values: banana, laranja
2) User click it. What I want: Show banana, laranja and pera as options. What happens: It shows banana, laranja in the list, show it and only after update the select (If I inspect the html code with fiebug, the pera option is there!). If I click again inthe select, the pera options appears normally and as the code above says, it appends another pera option in the select that only appears in the next click and so on.

I'm a little bit confused.. do you just want to update the select when the page loads? If so you can do:
CSS:
#teste {
display: none;
}
JS:
$(function(){
$('#teste').append('<option id="pera">pera</option>').val("pera").show();
});

I think this might be what you are searching for:
Using the value:
$('[name=options]').val( 3 );//To select Blue
To reset it use:
$('[name=options]').val( '' );
Using the text:
$('[name=options] option').filter(function() {
return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);
Link: http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu

i think you want to prevent showing multiple times the teste option.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#teste{
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(document).click(
function(){
if(!$('#teste').is(':visible')){
$('<option/>',{
'id' : 'pera',
'html' : 'pera',
'selected' : 'selected'
}).appendTo('#teste');
$('#teste').show('slow');
}
})
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>

Related

Trying to update the DOM with dropdown select

I want the content displayed to be manipulated by selecting a dropdown option. Here's what I have so far. It doesn't work.
HTML - here's an example of my dropdown.
<select id="dropdown">
<option value="Week1" id="Week1drop">Week 1 - Greetings, Common Adjectives & Planets</option>
</select>
The div below will be hidden by default using {display: none} in CSS.
<div id="week1">
<h1>Greetings, Common Adjectives & Planets</h1>
</div>
JavaScript - Below I've got an event listener to check for a change to the dropdown, which whill call the UpdateDom Function.
The function should be identifying that the user has selected Week1 on the dropdown and using Jquery .show() to make the Div visible.
document.getElementById("dropdown").addEventListener("change", updateDom);
function updateDOM () {
if (document.getElementById('dropdown').value == "Week1") {
$("#week1").show();
}
}
I hope this makes sense, does anyone know where I'm going wrong?
Apart from the typo you found yourself, if you have jQuery, USE it.
Also options do not have IDs
$("#dropdown").on("change", function() {
$("#week1").toggle(this.value == "Week1"); // same as $(this).val()
}).change(); // initialise on load
#week1 {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option value="">Please select</option>
<option value="Week1">Week 1 - Greetings, Common Adjectives & Planets</option>
</select>
<div id="week1">
<h1>Greetings, Common Adjectives & Planets</h1>
</div>

How to disable first option in Drop down select menu?

I have select menu option in right side of my website "I wish to sponsor". Default drop down menu set to "select" option I want when someone press go button page will not go anywhere. Currently when user press go button without selection option it goes to "404" page. How can I stop page to go somewhere without selection two given option in drop down?
Screenshot also attached and link is : http://ilmoamal.org/newsite2017/sponsor-now-testing/
enter image description here
Using CSS you can remove!
<style>
#link:focus option:first-of-type {
display: none;
}
</style>
You can use this in your footer.php file of WordPress theme. This will disable the "Go" button if no option is selected.
<script>
jQuery( document ).ready(function() {
jQuery(".wpcf7-form .submit input").prop('disabled', true);
jQuery(".wpcf7-form select option:first").prop('disabled', true);
jQuery("#link").change(function(){
var conceptName = jQuery('#link').find(":selected").text();
if(conceptName == "select"){
} else {
jQuery(".wpcf7-form .submit input").prop('disabled', false);
}
});
});
</script>
jQuery( document ).ready(function() {
jQuery(".wpcf7-form .submit input").prop('disabled', true);
jQuery(".wpcf7-form select option:first").prop('disabled', true);
jQuery(".wpcf7-form select option:first").prop('selected', true);
jQuery("#link").change(function(){
var conceptName = jQuery('#link').find(":selected").text();
if(conceptName == "select"){
} else {
jQuery(".wpcf7-form .submit input").prop('disabled', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form class="wpcf7-form">
<h4>I wish to sponsor</h4>
<p><select id="link"><option>Select</option><option value="http://ilmoamal.org/bms/apps_available.php?start=1&link=72f061b63526b44879240efb612646ed&project_id=1&submit=+Go+">A Child’s Education</option><option value="http://ilmoamal.org/bms/apps_available.php?start=1&link=72f061b63526b44879240efb612646ed&project_id=3&submit=+Go+">A Family Help</option></select></p>
<div class="submit"> <input onclick="go()" name="submit" value="Go" type="button" id="submit"> </div>
</div>
</form>
You can click on "Show Code Snippet" link above to RUN and test this code.
add below code in function.php file for remove select option
<?php
function myscript() {
?>
<script type="text/javascript">
$(document).ready(function()
{
$("#link").children().first().remove();
});
</script>
<?php
}
add_action( 'wp_footer', 'myscript' );
?>
I have seen that you use contact form 7 select box.
And also seen that you have set value for 2nd and 3rd option in select box but in first option there are no value for that option.
The best way is set the value # to first option which you want to disable.
Then let me know the result.
I mean
<option value="#">Select</option>
just add this in your script-
jQuery(document).ready(function(){
jQuery('#sidebar #link > option:first-child').attr('disabled', 'disabled');
});

Show a div on option selection

I have a selection menu (drop down list).
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
& the following div which located in somewhere in my page.
<div id="somediv">This is a string.</div>
I want to display the above div upon selecting the second item of the menu (id="two").
I have 2 questions: (1) What is the best way to keep this div hidden by default? I will just add display:none; to its styling, but maybe there is a better solution? (2) How can I make the div show up when the option of id="two" is selected? Any answer would be greatly appreciated.
So I wrote a simple jquery script that does what you described. Let me know if it fixes your problem. You can also do this with javascript, but I think jquery works for this just fine.
http://codepen.io/Francisco104/pen/vEPRgp
$('select').change(function(){
decide($(this));
});
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
};
For hiding it by default, using style="display: none"is the easiest. You could do it using jquery $('div#somediv').hide(); but I don't see any benefit to that other than you possibly wanting to keep the show/hide logic together.
Here are two simple solutions using a change() event.
If div#somediv should be shown permanently when option#two has been selected:
$("select").change(function() {
if ($(this).val() == 'anything') $('div#somediv').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
If div#somediv should be shown while option#two is selected and disappear if the user selects another option:
$("select").change(function() {
$('div#somediv').toggle($(this).val() == 'anything');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
You should probably give an id to the select as well, to make the jQuery selector less brittle.
So, I'd have a class for the div, let's say, is-hidden and my CSS will have .is-hidden { display: none; }. Then, do the following.
HTML:
<div id="somediv" class="is-hidden">This is a string.</div>
JS:
$div = $("#somediv");
$("select").on("change", function() {
$div.is(".is-hidden") || $div.addClass("is-hidden");
//Option 1
if ($(this).find(":selected")[0].id === "two") {
$div.removeClass("is-hidden");
}
//Option 2 (same as above, but a bit shorter)
$(this).find(":selected")[0].id === "two" && $div.removeClass("is-hidden");
});
Here is what you can do:
in your html file:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
You'll need to import the JQuery library (which I show you there right above the <select> element) so that you can execute your script.
In your css file:
#somediv {
display: none;
}
and finally here is the script that will show the dive when "plane" is selected
$('select').change(function(){
$('#somediv').css('display','block');
});
Take a look at this JSFIDDLE I made for you.
1) You can hide the div initially giving the css property display:none; or by setting its display property using javascript which will run in initial load.
2) You can listen to the onchange event of the selectfield and check if value is 'anything' then show the div by changing its display style property to block and hidden in other cases.
document.getElementById("somediv").style.display='none';
var showHideDiv=function(selectField){
var divElement=document.getElementById("somediv");
if (selectField.value=='anything')
divElement.style.display='block';
else
divElement.style.display='none';
}
<select onchange='showHideDiv(this)'>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv">This is a string.</div>
The simplest way to hide within HTML
<div hidden>content</div>
To display an hidden div
$(document).ready(function(){
$("select").change(function () {
$( "select option:selected").each(function(){
if($(this).attr("value")=="anything"){
$("#somediv").show();
}
});.
});
Display none works.
Have you tried keying into the onchange event? http://www.w3schools.com/jsref/event_onchange.asp?

Chrome Drop-Down List Problem

I have a problem with Chrome. I have a drop-down list. Except for Chrome, it works well. However with chrome it adds an empty element at first.
HTML Part:
<head>
<script type="text/javascript">
$(document).ready(function() {
townDistrictObject.bind({cityId:1});
});
</script>
</head>
<body>
<div class="left marginleft15">
<p>Town</p>
<p>
<select name="town1" id="townId" style="width: 152px;">
<option selected="selected" value="999999999">Whole Istanbul</option>
<option value="999999998">Anatolian Part</option>
</select>
</p>
</div>
<div class="left marginleft15">
<p>District</p>
<p>
<select id="districtId" name="districtid1" style="width: 174px;" >
<option selected="selected" value="0">Whole Districts</option>
</select>
</p>
</div>
</body>
There is something like that at script side:
var townDistrictObject = {
defaults : {
cityId :1,
townElementId : "townId",
districtElementId : "districtId",
allDistricts: true
},
bind : function(options) {
$.extend(this.defaults, options);
var that = this;
var opts = this.defaults;
var townElement = $('#' + opts.townElementId);
townElement.val(0);
}
};
Explanation of problem:
Firstly, there is an empty element at top of list.(It shouldn't be!)
Secondly, I will click one of them.("Whole Istanbul" for my example.)
Lastly, I check the list and that element at top disappears. Everything is OK after that time.
PS: I checked the code and I think that the problem is related to script side. Thanks for your help.
Could it be that you are doing:
townElement.val(0);
You are setting the dropdown value to zero, when there is no option with this value. Instead of zero, should you be using the value from the defaults?
The problem is setting with wrong id at this line:
townElement.val(0);
The answer with Jquery replacing it with:
townElement.get(0).selectedIndex = 0;

moving select options up and down via jquery

so I got this code working for Firefox and Chrome...what it does is it allows you to reorder the options within an HTML select form...but then when I tested the code via IE8, it's kind of patchy...it only works for the first few clicks and after that you have to click many times on the button for it to work..
Does anybody know any other code that allows you to reorder select field items that works perfectly in IE8?
<select id="list" multiple="multiple">
<option value="wtf">bahaha</option>
<option value="meh">mwaahaha</option>
</select>
<button id="mup">Move Up</button>
<button id="mdown">Move Down</button>
Add Item
Remove item
<script>
$(document).ready(function(){
$('#mup').click(function(){
moveUpItem();
});
$('#mdown').click(function(){
moveDownItem();
});
});
function moveUpItem(){
$('#list option:selected').each(function(){
$(this).insertBefore($(this).prev());
});
}
function moveDownItem(){
$('#list option:selected').each(function(){
$(this).insertAfter($(this).next());
});
}
Your code for changing the options works fine. It seems IE8 isn't handling a "fast" second-click with the click event but rather expects a double click to be handled.
Using my test code below, you'll notice that in IE8 writes out the following when Move Down/Up is pressed "fast":
Move Down Click
Move Down Double-Click
Move Down Click
Move Down Double-Click
But with FF/Chrome the following is printed:
Move Down Click
Move Down Click
Move Down Double-Click
Move Down Click
Move Down Click
Move Down Double-Click
Here's the code I'm using to test. I haven't done any tests to see if it's jQuery's event binders that are causing the issues.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
</head>
<body>
<select id="list" multiple="multiple">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button id="mup">Move Up</button>
<button id="mdown">Move Down</button>
<script type="text/javascript">
var $DEBUG = null;
$(document).ready(function ()
{
$DEBUG = $("#debug");
$DEBUG.append("Registering Events<br />");
$("#mup").click(moveUpItem);
$("#mdown").click(moveDownItem);
$("#mup").bind("dblclick", function ()
{
$DEBUG.append("Move Up Double-Click<br />");
});
$("#mdown").bind("dblclick", function ()
{
$DEBUG.append("Move Down Double-Click<br />");
});
});
function moveUpItem()
{
$DEBUG.append("Move Up Click<br />");
}
function moveDownItem()
{
$DEBUG.append("Move Down Click<br />");
}
</script>
<div id="debug" style="border: 1px solid red">
</div>
</body>
</html>
EDIT: I can confirm it is IE8 that is the problem. Swap this IE8-specific code in the $(document).ready() handler:
// $("#mup").click(moveUpItem);
$("#mup")[0].attachEvent("onclick", moveUpItem);
// $("#mdown").click(moveDownItem);
$("#mdown")[0].attachEvent("onclick", moveUpItem);
// $("#mup").bind("dblclick", function ()
$("#mup")[0].attachEvent("ondblclick", function ()
{
$DEBUG.append("Move Up Double-Click<br />");
});
// $("#mdown").bind("dblclick", function ()
$("#mdown")[0].attachEvent("ondblclick", function ()
{
$DEBUG.append("Move Down Double-Click<br />");
});
Example:
to move 3rd option before 1st option, we can use below jquery:
$('select[name="NameOfDropDown"] option:eq(2)').insertBefore($('select[name="NameOfDropDown"] option:eq(0)'));
I think this will give some ideas of how to do it, you can dynamically place any option before one known position just by knowing the values of both, the one to move and the one of the position:
How would you dynamically order an <option select> list using JQuery?
I know this one is a bit old, but I recently made this simple jQuery plugin to be able to reorder elements in a multiple select element.
Have a look and see if it helps for you, I tested in IE8,IE9,Chrome,FireFox,Opera.
http://fedegiust.github.io/selectReorder/

Categories

Resources