Button on click w/ selected value of <select> as parameter - javascript

I am new to web development and I'm trying to do this:
I have a <select> and I want the value of the selected option to be one of the parameters of a method that is called whenever a button is clicked.
So for example:
<select id="instructorSelector">
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
...
</select>
<button onclick="sendEmail(($('#instructorSelector').val()),...,...)" type="button">Send Email</button>
The problem with this is that it doesn't seen to detect when I've actually selected someone. I'm using freemarker templates but a general response as to how I should do this would be helpful too.
Also, how could I make it so the button is not clickable (or even visible) until the user actually selects something from the <select> ?
Thanks in advance! Sorry if this is an overly simple question.

You don't need to pass anything, what you need is a proper event handler:
<select id="instructorSelector">
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
...
</select>
<button id="btn" type="button">Send Email</button>
JS
$(function() {
$('#btn').hide();
$('#instructorSelector').on('change', function() {
$('#btn').show();
});
$('#btn').on('click', function() {
var select_value = $('#instructorSelector').val();
// use the value here
});
});

I would solve it like this:
disable the button in the beginning using the proper disabled-attribute
toggle this attribute if the value of the box changes, depending on something is selected or not
store the selectors in variables, so you don't need to re-query them all the time
HTML
<select id="instructorSelector">
<option value="">Please select</option>
<option value="abrown#gmail.com">Anna Brown</option>
<option value="jdoe#gmail.com">Jane Doe</option>
</select>
<button class="send_email" type="button" disabled="disabled">Send E-mail</button>
JavaScript
// example of a selector using a class name
var button = $('button.send_email');
// example of using a selector using the id of an element
var selector = $('#instructorSelector');
selector.change(function () {
if ('' == selector.val()) {
button.attr('disabled', 'disabled');
} else {
button.removeAttr('disabled');
}
});
button.click(function(event) {
sendEmail(selector.val());
event.preventDefault();
});
Demo
Try before buy

Try to use .chage() from jQuery http://api.jquery.com/change/ to make button visible
$('#instructorSelector').change(function () {
$('#id-of-the-button').show();
});
In this chang function you can also capture values of option $(this).val()

I highly recommend that you read jQuery Event Basics
You will need to understand how you can use selectors along with events to truly leverage the power of jQuery.
I think after reading about events you will see how click and change will greatly benefits the goals you have for your page.

Simplest Way: http://jsfiddle.net/rA4VJ/
<select id="instructorSelector">
<option value='none' selected>Choose Someone</option>
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
</select>
<button id="btn" type="button">Send Email</button>
var btn = document.getElementById("btn");
var elm = document.getElementById("instructorSelector");
elm.onchange = function (e) {
if (elm.value != 'none') {
console.log(elm.value);
btn.removeAttribute('disabled');
} else {
btn.setAttribute('disabled', 'disabled');
}
}

If you are using JavaScript, you can have the property onchange on the select, that can trigger a method that could check the value and make visible the the button. Use an option to indicate that there is no selection, and if that is the one selected, hide the button.
<select id="instructorSelector" onchange="something()">
<option value='selectone'>Select one</option>
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
...
</select>
<button id="button" style="display:none;" onclick="sendEmail(($('instructorSelector').val()),...,...)" type="button">Send Email</button>
function something(){
if ( $('#instructorSelector').val()!='selectone' ) {
document.getElementById("button").style.display = 'block';
}
else{
document.getElementById("button").style.display = 'none';
}
}

Related

How to check whether a dropdown is selected or search button is clicked

I want to fire ajax on dropdown change or search button is clicked (not on change of words). How can I check it in one go becuase I don't want to check it seperately.
For example - If I had to check on change of dropdown and on change of search input, I would use the following script
jQuery(function($){
jQuery( ".js-category, .js-input" ).on( "change", function() {
});
});
But I want to check on either dropdown is changed or search button is pressed and I want to check it one go.
The easiest and cleanest would probably be using a named function. Then register the function as callback of two separate events.
function eventHandler(event) {
console.log("Hello World!");
}
jQuery("#dropdown").on("change", eventHandler);
jQuery("#button").on("click", eventHandler);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option>foo</option>
<option>bar</option>
</select>
<button id="button" type="button">button</button>
try this
<select id="select">
<option>select</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>
<button id="button" type="button">click me</button>
<script>
$('#button, #select').on('click change', function(e) {
if(e.type==='change' && this.id =='select' || e.type==='click' && this.id =='button') {
alert('select');
}
});
</script>
You can wrap dropdown and button into the form and listen for submit (search button was clicked) and for change (dropdown selection was changed) events. Don't forget to prevent default submit behaviour in order to avoid unwanted redirections.
$("#js-form").on("change submit", (e) => {
e.preventDefault()
$("#test").html($("#test").html() + 0)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="js-form">
<select>
<option>1</option>
<option>2</option>
</select>
<input type="submit">
</form>
<div id="test">0</div>

On Page Load select option jquery like user behaviour (Real Time Change Event Fire)

I want to autoselect select box option on page load. Here is my code which is not working.
jQuery(document).ready(function(){
jQuery(".configure_supre_select_1 option:eq(1)")
.attr('selected',true)
.trigger('change');
});
You are triggering the selected option instead of the select - also use prop
$(function(){
$(".configure_supre_select_1 option:eq(1)").prop('selected',true);
$(".configure_supre_select_1").trigger('change');
});
Alternatively set the value
$(function(){
$(".configure_supre_select_1").val("firstOptionValue").change();
});
$(function() {
$(".configure_supre_select_1").on("change", function() {
$(".optdiv").hide();
var val = this.value;
if (val) {
$("#" + val.replace("OptionValue", "")).show();
}
});
$(".configure_supre_select_1").val("firstOptionValue").change();
$(".configure_supre_select_2 option:eq(1)").prop('selected',true);
$(".configure_supre_select_2").trigger('change');
});
.optdiv {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="configure_supre_select_1">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
<div class="optdiv" id="first">First is selected</div>
<div class="optdiv" id="second">Second is selected</div>
<hr />
Here I use your version <br/>
<select class="configure_supre_select_2">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
For make real time click by jquery i added below code. It used "Event".
For change select option on page load i use below code:
jQuery(".configure_supre_select_1").val(jQuery(".configure_supre_select_1 option:eq(1)").val()).change();
and then make it real time changing i use below code:
var dropdown = $("SelectAttributeId"); // Id of select box
var element = dropdown;
var event = 'change';
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);

How to call javascript or jquery function inside dropdown

I have the following HTML code:
<select name = 'category' id='category'>
<option value="a">A <a href="" class = "edit" id ='1'> Click here to edit </a> </option>
<option value="b">B <a href="" class = "edit" id ='b'> Click here to edit </a> </option>
</select>
I am trying like this:
$(document).on('click','.edit', editfunction);
function editfunction() {
alert('hi');
//call here ajax code
}
Firstly your HTML is invalid; you cannot have a elements inside an option:
<select name="category" id="category">
<option value="a">A</option>
<option value="b">B</option>
</select>
To do what you require you can hook to the change event of the select, not the click of the a within the option. You can then use $(this).val() to get the selected value in editFunction():
$(document).on('change', '#category', editfunction);
function editfunction() {
var value = $(this).val();
console.log(value);
// AJAX...
}
Try using the following
$('#category').on('change', function(){
editfunction( $(this).val() );
})
function editfunction(val){
// Make your ajax call here
}
And You actually dont need the tag inside to make this happen
I think this is what u want JSFIDDLE example

Remove the first select option

I'd like to remove the first option of an select tag when I click on the select tag. Is this possible?
I don't want to see the first option after that click.
Thanks for any help.
You can remove the first option on click with jQuery.
$(document).on('click', 'select', function() {
$(this).find('option').get(0).remove();
});
This simply removes the first option of a select tag on click. You need to add an if statement to check if it was already removed.
There's also a simple no-javascript solution:
<select>
<option style="display: none">--Choose--</option>
<option>Cheese Cake</option>
<option>Hot Pockets</option>
<option>Sausage</option>
<option>Cookies</option>
<option>Bacon</option>
</select>
(Copied from the comments from #chipChocolate.py)
If you use bootstrap add placeholder attribute in your select.
If your not
<select required>
<option value="" disabled selected>Select your option</option>
<option value="1">1</option>
</select>
// to remove first...
document.getElementById("element_id_str").options[0].remove();
//to remove the lot...
document.getElementById("element_id_str").options.length = 0;
<select required>
<option value="" disabled selected hidden>Select your option</option>
<option value="1">1</option>
</select>
Probably you just want this:
<select required>
<option value="" hidden>Select your option</option>
<option value="1">1</option>
</select>
A very naive way of doing this:
$("#selector").change(function(evt) { //listen to changes of selection
var theElement = $(this);
if (!theElement.data("selected")) { //check if flag is not set
theElement.children("option")[0].remove(); //remove 1st child
theElement.data("selected", true); //set flag, so it doesn't continue removing items for every change
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selector">
<option>--Choose--</option>
<option>Apple</option>
<option>Banana</option>
<option>Papaya</option>
</select>
If you want to remove the first option use this
$(document).ready(function()
{
$("select").children().first().remove();
});
If you want to remove the first option after clicking on the select box use this
$(document).ready(function()
{
var removed=false;
$(document).on("click","select",function()
{
if(!removed)
{
$(this).children().first().remove();
removed=true;
}
});
});
Javascript:
document.getElementById("SelectId")[0].remove();
Get the first option in the select and remove it.
I had the same problem, but the solutions above just work with one form, not with many. I added some extra code in order to validate it for many in your form:
$(document).ready(function()
{
$(document).on("change","select",function()
{
var x = $(this).children().first().attr("name");
var n = x.localeCompare("todelete");
if (n == 0)
$(this).children().first().remove();
});
});
Where "todelete" is the name for all first elements [0] defined inside the
Please select value //all first elem must have the same name
"> //the others another name (can be the same BUT not "todelete")
You need the id or class to remove the item. While testing and debugging I found 'option:first' fails to remove the item. But 'option:first-of-type' always does the work. You can get more info about 'first-of-type' here :first-of-type
$("#ID_or_.CLASS option:first-of-type").remove();

How to select option in select list using jquery

i have a form that has select element
<select name="adddisplaypage[]" id="adddisplaypage" multiple="multiple">
<option value="all" label="all">all</option>
<option value="index" label="index">index</option>
<option value="tour" label="tour">tour</option>
<option value="aboutus" label="about us">about us</option>
<option value="contactus" label="contact us">contact us</option>
<option value="destination" label="destination">destination</option>
<option value="reservation" label="reservation">reservation</option>
</select>
can anyone help me to select this option (multiple select) on click i.e the option gets selected when clicked, and deselected if selected on click.
I realized I may have misunderstood your question. Something like the following should work, though I'm not sure about browser support:
$('#adddisplaypage option').click(function(e) {
e.preventDefault();
var self = $(this);
if(self.attr('selected') == '') {
self.attr('selected', 'selected');
} else {
self.attr('selected', '');
}
});
In your click() handler, you could write something like:
$("#adddisplaypage").val("index");
That should select "index", for example.
You can pass an array to the .val() method. For instance:
$('#adddisplaypage').val(['index', 'tour']);

Categories

Resources