Comparing each of the <option>s in a <select> element using jQuery - javascript

I am writing a plugin for WordPress and am confused as to how to compare the user-input (got from an <input> element) to a set of <option> elements in a <select> element.
At the moment I am doing the following:
$('button#test_button').click(function(event) {
event.preventDefault();
// Get the text in the input box:
var input_text = $('input#input_test').text();
$("#selectId > option").each(function() {
if ($(this).text() == input_text) {
alert("Alert Triggered");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input_test"></input>
<select id="selectId">
<option value="hello">Foo</option>
<option value="test">Test</option>
</select>
<button id="test_button">Click me!</button>
However, if you run the snippet you can see that the alert is never triggered, but I'm not sure why? I'm new to JavaScript so I'm not aware of any intricacies to the language, so this is probably a simple query, but I'd be grateful for any assistance.

You need to use val() method to get input value. And you have a typo of getting text content of <option> tag. Should be $(this).text(), not $(this).text
$('button#test_button').click( function(event) {
event.preventDefault();
// Get the text in the input box:
var input_text = $('input#input_test').val();
$("#selectId > option").each(function() {
if( $(this).text() == input_text )
{
alert("Alert Triggered");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input_test"></input>
<select id="selectId">
<option value="hello">Foo</option>
<option value="test">Test</option>
</select>
<button id="test_button">Click me!</button>

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

Showing and hiding select boxes using javascript/

I have a little bit of test code that intends to have a select box display when a certain option is selected and then hide when that option is changed.
HTML:
<form>
<select id="sel1" name="sel1" class="chzn-select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="sel2" name="sel2" selected="selected" style="display:none">
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
JS:
var selCategory = $('#sel1');
$(selCategory).change(function () {
$('option:selected').each(function () {
if ($(this).text() ==='2') {
$('#sel2').show();
}
else if($(this).text() ==='1') {
$('#sel2').hide();
}
else if($(this).text() ==='3') {
$('#sel2').hide();
}
});
});
This bit of code works great if only this:
if ($(this).text() ==='2') {
$('#sel2').show();
}
Is the JavaScript but falls down when adding the else if statements. Also would it be better to display the select box itself or a containing div Tag? The only reason the second select box isn't a chosen-select is that chosen doesn't seem to like elements that are already hidden (problems with width).
Any help would be appreciated.
Your $('option:selected') selector is looking at the options from all select elements, not just #sel1. So #sel2 is shown (due to "2" selected in the #sel1), then immediately hidden (due to "1" selected in #sel2 itself). Make sure you're looking only at the value you want:
var selCategory = $('#sel1');
selCategory.change(function () {
selCategory.find('option:selected').each(function () {
if ($(this).text() =='2') {
$('#sel2').show();
}
else {
$('#sel2').hide();
}
});
});
I would make it easier, grab the value and concatenate the sel ID from that:
$("#sel1").change(function() {
$("select:not(#sel1)").hide(); //hide other selects, excluding #sel1
$("#sel" + this.value).show();
});

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

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';
}
}

Jquery selectmenu plugin with text input option

I need jquery plugin which would transform my simple
<select>
<option>text</option>
</select>
In to fully customizable list something like a <lu> list or list of <div>, i have found quite a lot of this kind of plugins, but none of them have option to type something in and set it as an option.
Lets say i have kind of list:
<select>
<option value="text">text</option>
<option value="other">other</option>
</select>
Now i want other option transform into <input type="text" />, and i'm quite sure there has to be plugin which does just that.
I have made an example how should it look, on the left is my current plugin and on the right is what i need, i know i could edit my current plugin but it's just way to big for me and it would take to much time.
There is no jQuery plugin which does exactly that. However, there is a jQuery UI selectmenu plugin, which converts a select element to a html representation such that you can style the select menu. This plugin also offers a callback for formatting text, such that in our case, we could format our 'other' option into an input box.
Suppose we have the following select:
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
<option>Other</option>
</select>
We can create a selectmenu with this plugin using:
$(function(){
selectMenu = $('select#otherselect').selectmenu({
style:'popup',
width: 300,
format: otherFormatting
});
});
In here the function otherFormatting is a function which will format our Other option. This is our function:
var otherFormatting = function(text){
// if text contains 'Other' format into Other input box...
if ( text == "Other" ) {
var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
var input = $('<input class="other" type="text" value="Other..."/>');
return $('<span/>')
.append(input)
.append(button)[0].outerHTML;
}
return text;
}
The selectOther function that is called when the button is clicked, is a function we will extend the plugin with. This function, activated when the button is clicked, will set the values of our select, such that we can easily submit it using a form. But also, set the value which is displayed in the new selectmenu (instead of showing an input box in the select box).
We need to extend this plugin, which is a jQuery UI widget basically. However, since the plugin binds some events which make it impossible for us to get the input field and button working, we need to unbind some of these. We do this when we open the select menu. For this we need to override the open function of the widget, call our function that unbinds some events and then open the menu using the original open function.
Putting this all together:
<!DOCTYPE html>
<html>
<head>
<title>Demo Page for jQuery UI selectmenu</title>
<link type="text/css" href="../../themes/base/jquery.ui.all.css" rel="stylesheet" />
<link type="text/css" href="../../themes/base/jquery.ui.selectmenu.css" rel="stylesheet" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.selectmenu.js"></script>
<style type="text/css">
body {font-size: 62.5%; font-family: "Verdana",sans-serif; }
fieldset { border: 0; }
label, select, .ui-select-menu { float: left; margin-right: 10px; }
select { width: 200px; }
</style>
<script type="text/javascript">
// We need to able to call the original open method, save intoIf you need to call original method
var fn_open = $.ui.selectmenu.prototype.open;
$.widget("ui.selectmenu", $.extend({}, $.ui.selectmenu.prototype, {
open : function() {
// Every the selectmenu is opened, unbind some events...
this._unbindEvents();
fn_open.apply(this, arguments);
},
_unbindEvents : function() {
var el = $(this.list).find('li:has(input.other)').eq(0);
// unbind events, we need a different event here...
el.unbind('mouseup');
el.unbind('mousedown');
el.bind('mousedown', function() {
// We need to call focus here explicitly
$(this).find('input.other').eq(0).focus();
// Empty field on click...
if ( $(this).find('input.other').eq(0).val() == 'Other...' )
$(this).find('input.other').eq(0).val("");
});
// Unbind keydown, because otherwise we cannot type in our textfield....
this.list.unbind('keydown');
// We only need to return false on the mousedown event.
this.list.unbind('mousedown.selectmenu mouseup.selectmenu');
this.list.bind('mousedown', function() {
return false;
});
},
selectOther : function(el) {
var button = $(el);
// li item contains the index
var itemIndex = button.parent().parent().parent().data('index');
var changed = itemIndex != this._selectedIndex();
// Get the value of the input field
var newVal = button.prev().val();
this.index(itemIndex);
// Update the display value in the styled select menu.
this.newelement.find('.' + this.widgetBaseClass + '-status').html(newVal);
// Update the value and html of the option in the original select.
$(this.element[0].options[itemIndex]).val(newVal).html(newVal);
// Call the select, change and close methods
var e = jQuery.Event("mouseup");
this.select(e);
if ( changed )
this.change(e);
this.close(e);
}
}));
var selectMenu;
$(function(){
selectMenu = $('select#otherselect').selectmenu({
style:'popup',
width: 300,
format: otherFormatting
});
});
function selectOther(el) {
// Call our self defined selectOther function.
selectMenu.selectmenu('selectOther', el);
}
//a custom format option callback
var otherFormatting = function(text){
// if text contains 'Other' format into Other input box...
if ( text == "Other" ) {
var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
var input = $('<input class="other" type="text" value="Other..."/>');
return $('<span/>')
.append(input)
.append(button)[0].outerHTML;
}
return text;
}
</script>
</head>
<body>
<h2>Select with Other option input field</h2>
<fieldset>
<label for="otherselect">Select a value:</label>
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
<option>Other</option>
</select>
</fieldset>
<button onclick="console.log($('#otherselect').val());">Test</button>
</body>
</html>
To try this, download the plugin here and make sure the urls to the js/css files are correct. (I have put this html file into the demos/selectmenu folder and it works...). Ofcourse you can replace the button with an image.
Try this, this little script will create a text input after a select box if the select box value is other. The new text input as the same name of the select so that its value overwrite the one set by the select (as it is other)
If the value is something else than other we just check for the text input presence and remove it (so it doesn't overwrite the select value)
http://jsfiddle.net/cW725/1/
HTML
<form>
<p>
<select>
<option value="text">text</option>
<option value="text">text</option>
<option value="text">text</option>
<option value="other">other</option>
</select>
</p>
<p>
<select>
<option value="text">text</option>
<option value="text">text</option>
<option value="text">text</option>
<option value="other">other</option>
</select>
</p>
</form>
​
jQuery
$(function() {
// bind all select on change
$('select').on('change', function() {
// if value is other
if ($(this).val() == 'other') {
// add a text input we match the name so that this input overwrite the select one as after in the form
$(this).after('<input type="text" name="' + $(this).attr('name') + '" class="otherInput" />');
} else {
if ($(this).next().is('input.otherInput')) {
$(this).next().remove();
};
};
});
});​
I was looking for a jquery 'select or edit' solution, and found this can be done with help of select2 plugin.
Turned out to be pretty simple solution that does exactly what I wanted.
HTML:
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
</select>
JS:
$('#otherselect').select2({tags: true});
Example:
https://jsfiddle.net/h0qp37jk/
You might check out chosen.js - it might fit your needs. Might be easier that making something from scratch. Good luck.

Categories

Resources