Setting select box using jQuery on document ready - javascript

Can anyone suggest how I get to change the selected item in a select menu with jQuery - I've tried the following but without success. Using this snippet how would I use jQuery to set to value '5' for example (eg Cambridgeshire) as the 'selected' value.
<script type="text/javascript">
$(document).ready(function() {
$('#county_id option[value=3]').attr('selected', 'selected');
});
<html>
<select name="county_id" id="county_id">
<option value="1">Bedfordshire</option>
<option value="2">Berkshire</option>
<option value="4">Buckinghamshire</option>
<option value="5">Cambridgeshire</option>
</select>
</html>

You just need to use the val method.
$('#county_id').val(5);

This should work in most cases and will automatically select the correct option.
<script type="text/javascript">
$(document).ready(function() {
$('#county_id').val(3);
});
</script>

Should be able to use a jquery selector than edit the attributes.
$('input:radio[name=county_id]')[3].checked = true;
or
$('input:radio[name=county_id]:nth(3)').attr('checked',true);
In this case, 3 is the counter associated with Cambridgeshire (remember, counting starts at zero).
via

Related

Pre-select option in dropdown menu with URL

I'm working with this code snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// <![CDATA[
$(document).ready(function() {
// Parse your query parameters here, and assign them to a variable named `queryParams`
var option = queryParams.type;
$("#GCValue").val(option);
});
// ]]>
</script>
I don't have a lot of latitude with how I can affect the page, this is in the <body> section of the page, since I don't have access to the <head> tag.
I have this form:
<select id=GCValue>
<option val="10">10</option>
<option val="25">25</option>
<option val="50">50</option>
<option val="100">100</option>
<option val="250">250</option>
</select>
and I would like to use the URL of the page to select one of these five options (currently default is 10). I think it's supposed to be either https://www.mywebsite.com/gift-card/?type=2 or https://www.mywebsite.com/gift-card/?GCValue=2 but neither work. I'm pretty new to JS and JQuery, so I know I have to be doing something wrong. Any help appreciated.
According to your code your URL should be something like
https://www.mywebsite.com/gift-card/?type=10
You have to pass the option values to the URL instead of the option indexes based on your current code.

How to access the javascript variable inside html tags

I wanted to added javascript variable inside html code.
Here is my code:
<select id="currentrun" name="currentrun" >
<option value=""><script>selectedrun</script></option>
</select>
and my js function
var currentrun="";
var selectedrun="";
function setCurrentRun()
{
currentrun = document.getElementById("runlist");
selectedrun = currentrun.options[currentrun.selectedIndex].value;
}
But this doesn't work.
Can anyone help me to do this.
Thanks in advance.
You don't have to run the script like that.
The value of the currentrun can be retrieved as:
document.getElementById('currentrun').value
And for completeness, if you want to trigger a JavaScript function call each time the selection is modified, do this:
<select onchange="my_function();">
<option>...</option>
</select>
It seems like you are trying to set the text of the option element with javascript. Here is one way you can do it using the id of the element to get it and then set the text property of the element to your javascript variable:
<select id="currentrun" name="currentrun" >
<option id="currentoption" value=""></option>
</select>
<script>
document.getElementById("currentoption").text = selectedrun;
</script>
Be sure to put any necessary javascript that declares and sets the selectedrun variable before the above script.

jquery .val() strange behavior on dropdowns

I have a html <select> tag with some <option>s. Something like this:
<select id="season">
<option value="">Select an option</option>
<option value="1">Spring</option>
<option value="2">Summer</option>
<option value="3">Autumn</option>
<option value="4">Winter</option>
</select>
And I have this javascript code:
<script>
$(document).ready(function(){
$("#season").val("1");
});
</script>
This does not select "Spring" option and remain in "Select an option" option! But when I use
$(document).ready(function(){
setTimeout(function(){
$("#season").val("1");
}, 100)
});
This works correct! What is the problem? Any help would be greatly appreciate.
Try This
<script>
$(document).ready(function(){
$("option[value='1']").attr('selected','selected');
});
</script>
Above mention code will work.
even below mention your code will work, but script section should below all the HTML code and before the body close tag. Because once jQuery or javaScript start executing at that time HTML DOM will available and script can able to select that DOM.
<script>
$("#season").val("1");
</script>
In your code once you add setTimeout and your script is able to select the option because you are delaying by 100 micro second, it means before executing your script HTML DOM are available that is why you are able to select the DOM
<script>
setTimeout(function(){
$("#season").val("1");
}, 100)
</script>
on page load is called after all resources is loaded whereas jquery ready is called when dom is loaded so basically ready gets called before on-load. Hence it does not work

Select all multi-select Option using javascript

I tried to select all options of multi-slect flower[ ] using javascript but nothing happened when I click on submit, please tell what wrong ?
<html>
<head>
<script language="javascript" type="text/javascript">
$("#submit").click(function() {
$('#flower option').each(function() {
$(this).attr('selected', true);
});
});
</script>
</head>
<body>
<form method="Get" action="#">
<select name="flower[ ]" id="flower" multiple>
<option value="flower">FLOWER</option>
<option value="rose">ROSE</option>
<option value="lilly">LILLY</option>
<option value="jasmine">JASMINE</option>
<option value="lotus">LOTUS</option>
<option value="tulips">TULIPS</option>
</select>
<input type="submit" id="submit" name="submit" value="submit">
</form>
</body>
</html>
You must put your javscript click function inside document ready function. Like this
$(document).ready(function(){
$("#submit").click(function(e){
$('#flower option').each(function () {
$(this).attr('selected', true);
});
});
});
Cheers.. :)
You are missing:
$(document).ready(function(){
above your script and then close it with:
});
but as mentioned above:
$('#flower option').attr('selected', true);
Should do the trick as well
$('#flower option').attr('selected', true);
You've already selected all of the options so the each loop is unnecessary.
Put your javascript on the end of body or use $(document).ready(). It must be executed when form is already rendered.
You can do it with .val(). $('#flower').val(ARRAY OF VALUES), i.e.
$('#flower').val(['lilly', 'lotus']);
For selecting all you can use
$('#flower').val($('#flower option').map(function(){
return $(this).attr('value');
}));
You do not specify in your question, but it looks like you are using jQuery. If you do, first make sure that you have placed your code inside of a $(document).ready(function(){...}) block so that you are waiting until the DOM is ready for you to begin attaching event listeners. Also, you shouldn't need the .each(function(){...}) call. Finally, to ensure cross-browser compatibility and to conform to standards, set the selected attribute to 'selected' rather than true. See code below.
$(document).ready(function() {
$('#submit').click(function() {
$('#flower option').attr('selected', 'selected');
});
});
EDIT
Actually, it's better to use jQuery's .prop() here, since using .attr() only is only to be used for setting the option's initial state. So...
$(document).ready(function() {
$('#submit').click(function() {
$('#flower option').prop('selected', true);
});
});
More info on this can be found in this question...
Jquery select all values in a multiselect dropdown

append() text value to div onclick()

I am creating an instant messenger using jquery and am having trouble taking the message typed into the message field after clicking the "send" button
I have the html
<body>
<div class="main-window">
<div class="chat-screen"></div>
<div class="bottom-wrapper">
<input class="text-bar"></input>
<input type="button" value="Send"class="send-btn">Send</input>
</div>
</div>
<body>
and I have tried to append it using this jquery
$('.send-btn').click(function() {
$(".text-bar").text().appendTo(".chat-screen");
});
But it doesn't seem to work. Can someone please point me in the right direction?
JSFiddle
you need .val()
change
$(".text-bar").text()
to
$(".text-bar").val()
you code becomes
Fiddle DEMO
use .append()
$('.send-btn').click(function () {
$(".chat-screen").append($(".text-bar").val());
});
Clear Textbox and new chat in new line.
$(document).ready(function () {
var chat_screen = $(".chat-screen");
var text_bar = $(".text-bar")
$('.send-btn').click(function () {
chat_screen.append(text_bar.val() + '<br/>');
text_bar.val('');
});
});
Updated Fiddle DEMO
The .text() (and correct .val()) functions return strings, not jQuery objects, and therefore don't have the appendTo() function available on them. You'll need to do this instead:
$('.chat-screen').append($('.text-bar').val());
Also make sure that, if the script is in the <head> of your HTML page, or comes before the actual HTML of the elements, you wrap it in a DOM ready handler:
$(document).ready(function() {
$('.send-btn').click(function(){
$('.chat-screen').append($('.text-bar').val());
});
});
And, of course, check that jQuery is being loaded correctly (it wasn't in your jsFiddle at all).
Since this is going to (probably) be running a lot of times, you'd want to cache the selectors for the chat screen and the text input, like so:
$(document).ready(function() {
var $chatscreen = $('.chat-screen'),
$textbar = $('.text-bar');
$('.send-btn').click(function(){
$chatscreen.append($textbar.val());
$textbar.val('');
});
});
Updated jsFiddle
Here is you fiddle updates: jsfiddle
Use val() instead text()
$('.send-btn').click(function(){
//$(".text-bar").val().appendTo(".chat-screen");
$(".chat-screen").append($(".text-bar").val())
$(".chat-screen").append('<br />')
});
please see http://jsfiddle.net/K95P3/15/
Several issues:
Add space between value and class attributes in input
Change .text() to .val() - inputs don't have text nodes, just values
Use $('.chat-screen').append($(".text-bar").val());
Make sure you have jQuery included
See updated fiddle http://jsfiddle.net/K95P3/11/
Try this.
$('.send-btn').click(function(){
$('.chat-screen').append($(".text-bar").val());
});
Actually, you really should append an html tag, not just text. I mean, you could, but shouldn't.
What i would recommend is this:
Create a base container for a message like:
<div class="message-container" style="display:none;">
<span class="message"> </span>
</div>
You then clone this container, stuff it the value of the input in the chat and append it to the chat screen.
The code could be something like:
$('.send-btn').click(function(){
var container = $('.message-container:hidden').clone(true).show();
container.find('.message').text($(".text-bar").val());
container.appendTo($('.chat-screen'));
});
Append text and dropdown value sametime
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
//var x=$("#cars option:selected").text();
//var y=$("#bus").val();
//alert(''+x+' '+y+'');
$(".chat-screen2").append($("#cars").val()+'<br/>');
$(".chat-screen").append($("#bus").val()+'<br/>');
$("#bus").val('');
});
});
</script>
</head>
<body>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<input id="bus" type="text">
<button type="submit">submit</button>
<br><br>
<div class="chat-screen2" style="float:left;"></div>
<div class="chat-screen" style="float:left;margin-left:10px;"></div>
</body>
</html>

Categories