I am trying to utilize the JQuery if statement to create a form that will allow employees to create a custom verbal script for their customers. Basically the JQuery Plugin will simply append input field values to a dialogue to be read by the employee to the customers.
I've had no issue with the JS written to append the contents of text-fields and select boxes to the dialogue but seem to be unable to figure out the most crucial part. I want to be able to show or hide information relevant to specific states based upon the value of a select box input field.
Below is a single example of my attempt at utilizing the if/else statement to do so.
HTML:
<select name="state_select" class="state_select">
<option value="CT">Connecticut</option>
</select>
<p class="ct_opt">Lorem Ipsum</p>
Css:
.ct_opt {
display:none;
}
JQuery:
$(document).ready(function(){
if ($("select.state_select").val() == "CT") {
$("ct_opt").show();
} else {
if ($("select.state_select").val() != "CT")
$("ct_opt").hide();
}
});
From what I understand, this should allow the targeted text to stay hidden unless its corresponding state is selected. However, it seems to do nothing at the current moment :(
Any suggestions would be greatly appreciated.
$(document).ready(function() {
$('.state_select').val('CT');
$('.state_select').on('change', function() {
console.log('click');
if($(this).val() == 'CT') {
$('.ct_opt').show();
}
else if ($(this).val() == 'noshow') {
$('.ct_opt').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="state_select" class="state_select">
<option value="CT">Connecticut</option>
<option value="noshow">Dont Show</option>
</select>
<p class="ct_opt">Lorem Ipsum</p>
$('select.state_select') will select an array of select objects with the class state_select. If you only have one state_select you should change this selector to $('#state_select'). There is no point in using $('select#state_select') (although valid) since there can only be a single id per page. You could use your current selector but you will need to call .first() to get the first item in the array of elements matching that selector.
Additionally as Ragnar pointed out there is no element named 'ct_opt' so you need to change your selector to $('.ct_opt') to target the class.
Use .ct_opt because it's a class and execute your code when selection changes:
$(document).ready(function(){
$("select.state_select").change(function(){
if ($(this).val() == "CT")
$(".ct_opt").show();
else $(".ct_opt").hide();
});
$("select.state_select").change(); //call change event when page loads
});
You can use $() because it's equivalent to document ready:
$(function(){
$("select.state_select").change(function(){
if ($(this).val() == "CT")
$(".ct_opt").show();
else $(".ct_opt").hide();
});
$("select.state_select").change(); //call change event when page loads
});
Related
I have this Show/Hide select box (JS Fiddle) that gets a classname from a selected option and hides a corresponding unordered list item. I am at a loss to use replace() to replace the text Hide with Show or vice versa when an option is clicked.(e.g Show Month should become Hide Month on click.)
I also want to change all the options back to Hide when I click the Show All option.
When I used
findoption.replace('Hide','Show'); I got this Uncaught TypeError: undefined is not a function error. Can anyone show me how to do that? Any help would be appreciated.
JS Code:
$(document).ready(function(){
$(".showhidelist").change(function() {
$this = $(this);
var findoption = $this.find('option:selected');
var selected = findoption.data('hide');
var show_hide_li = $("."+selected);
if (show_hide_li.css("display") == "none") {
show_hide_li.show();
/* Want to Replace the text Hide with Show */
}
else if (show_hide_li.is(':visible')){
show_hide_li.hide();
/* Want to Replace the text Show with Hide */
}
else if (selected == "Reset") {
$('li').show();
/* Want to Replace the text Show with Hide if it's true */
}
});
});
HTML
<select class="showhidelist">
<option data-hide="Reset">Show All</option>
<option data-hide="year">Hide Year</option>
<option data-hide="month">Hide Month</option>
<option data-hide="day">Hide Day</option>
</select>
<ul id="list">
<li class="year">2004</li>
<li class="month">Feb</li>
<li class="day">17</li>
<ul>
findoption is returns a jquery array, so you would need to access the first element there. I think the following will achieve what you're looking for (as far as the selected element goes).
findoption[0].innerHTML = findoption[0].innerHTML.replace('Show','Hide');
I'm not sure what you're really doing - this gets a little quirky, since you have the show/hide all and you'll have to go through the whole list to update them when you do. Also - you aren't getting a selected event when you re-select what's already selected.
UPDATE: this includes how to update all items in the list using each()
jsfiddle: http://jsfiddle.net/hk4wg/15/
You are not getting the text() into the replace, and you could use the function that .text() has to replace the text.
findoption.text(function(_,text){ return text.replace('Hide', 'Show')});
Change the word 'Hide' or 'Show' depend on what you want.
Update:
I read in caspian comment, that you problem now is that you could not re-click an option clicked, try restarting the select to first option like:
$(".showhidelist").prop('selectedIndex',0);
I have a multiselect box having some options which i am able to select or disable via jquery, but i am not able to make them do both at the same time. How can i do that via jquery ??
Here's what i was doing - JSFiddle
In this example i am selecting an option on load and after that disabling it, but the option is still de selectable. I want to keep it selected and disabled all the time.
For now i am using click method to keep it selected by adding this line:
$('#multiSelect').click(function()
{$('#multiSelectoption[value="three"]').attr('selected',true);});
EDIT:
People are posting the solution where we select the option again on click, which i already have posted in my question. What i wanted to know is that if there exist some better solution as this one does not look good.
js fiddle:
http://jsfiddle.net/Tf5ZZ/5/
jquery:
//disabling on load:
$('#multiSelect option[value="three"]').prop('disabled', true);
$("#multiSelect option").on('click',function() {
$('#multiSelect option[value="three"]').prop('selected',true);
});
If the point is to prevent the value of the select box from being changed after it's set then you should disable the select box instead of just the option item.
$('#multiSelect option[value="three"]').prop('selected',true);
$('#multiSelect').prop('disabled',true);
See this fiddle for demonstration: http://jsfiddle.net/zKbVm/1/.
Also, the difference between prop() and attr() is that attr() gets/sets the element's attributes (which reflect the inital state of the element) and prop() gets/sets its properties (which represent the current state of the DOM node). See https://stackoverflow.com/questions/5874652/prop-vs-attr for more information.
Here is a small piece of jQuery to solve your problem.
$("#multiSelect option").click(function()
{
$("#multiSelect option[value='three']").prop("selected", true);
});
<select multiple="multiple" size="3">
<option value="1" selected>One</option>
<option value="2" disabled>Two</option>
<option value="3" disabled>Three</option>
</select>
I guess you could handle that in the create event of multiselect which is called after the widget gets created.
Below is the code snippet which I am using in the current application I am working on;
create: function (event, ui) {
$(this).multiselect("widget").find(":checkbox").each(function () {
var checkBoxValue = $(this).val();
// Using linq.js to query the fields and determine whether
// the field is required in my case.
// Replace this if statement with your own logic here
if (Enumerable.From(CHAMP.cache.fields).Count(function (x) {
return x.Id.toString() == checkBoxValue && x.IsRequired == true;
}) > 0) {
$(this).attr("checked", "checked");
$(this).attr("disabled", "disabled");
}
});
}
I'm loading some div content using a navigation and i've got most of the content working properly. However I'm now trying to set up:
http://www.bulgaria-web-developers.com/projects/javascript/selectbox/
On a select dropdown, however the styling is called using the following:
$(function () {
$("#select").selectbox();
});
And I can't see how I can I can apply:
$(document).on('mousedown', '.nav-link', function() {
To it for when it first appears? Any advice much appreciated, cheers.
UPDATE
Nevermind, i've done it.
SECOND UPDATE
Ok i've just found 2 problems. Firstly, I made it show by using:
if (href == 'requestedpage.php') {
$(function () {
$("#select").selectbox();
});
};
And when the page loads the first time, the selectbox is styled properly, however if you go to another page and then go back, it doesn't apply the style second time around?
The other problem i've got is that when you click on the options, the dropdown makes your selection, but all of the options in the select list remain in view.
HTML code is:
<select id="selectlist" name="selectlist" onchange="updatevariable(this.value)" tabindex="1">
<option value="">-- Select Quantity --</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
Sorted problem 2 by removing onchange event!
Thanks in advance to anyone who can help me out.
If it's not applying the styling when you navigate back, it might be as simple as setting a flag in your callback.
One way to do this is to send a flag value to a hidden input field which will post to your server on page-submit. This means when you navigate back, you can check if the flag is there, if it is, apply the styling.
Alternatively, if you are building this application for browsers which support HTML5, you can save to the sessionStorage in your AJAX callback.
So, where you're checking the href, add this:
if (href == 'userarea-page1.php') {
$(function() {
$("#select").selectbox();
sessionStorage.selectFlag = "true";
});
};
Then, above your $("a.nav-link").click event (in your document.ready) you can check if this is has been set. If it has, apply the styling.
$(document).ready(function() {
if (sessionStorage.selectFlag == "true") {
$("#select").selectbox();
}
$("a.nav-link").click(
...
);
);
This will take care of maintaining the styling state between pages. Just make sure you clear the flag if you ever want to remove the styling, otherwise it'll be applied forever.
I'm not sure why you're setting the styling via javascript if you want it on page load, but if that is the way you're doing things try this may help:
$(document).ready(function() {
$("#select").selectbox();
);
This is my first detailed question on SO.
Hi, so I have a form and have many instances where I want to show a text field after a drop down list when the user selects the "Other" option in the drop down list.
I am using a standard naming convention and am wondering, do I have to have as many functions as DDL/text field pairs in the document, or can I have a single function I can call on a class of DDLs? Here's the HTML:
<label for="spotter">Spotter:</label>
<select id="spotter" required>
<option value="Snoop Dogg">Snoop Dogg</option>
<option value="MC Escher">MC Escher</option>
<option value="Linus Thorvalds">Linus Thorvalds</option>
<option value="Other">Other</option>
</select>
<br/>
<div id="spotter_other_div"><label for="spotter_other">Other Spotter:</label><br><input type="text" name="spotter_other" id="spotter_other" size="50" required/></div>
and here's the jQuery/javascript:
$(document).ready(function(){
$("#spotter").change(function () {
//alert("You just changed the value of the #spotter drop down menu.");
if ($(this).val() == "Other" )
//alert("You just changed the value of the #spotter drop down menu to 'Other.'");
$("#spotter_other_div").css("visibility", "visible");
else
$("#spotter_other_div").css("visibility", "collapse");
});
});
The initial state of the div containing the text field is "collapse" in css.
I am learning jQuery and I'm at the point where I know how to do something for a general case, and I'd like to see if this is a function I can write, or if I have to do it explicitly.
Note that the page is a work in progress so any suggestions are welcome (e.g. use a span instead of a div to contain the text field, etc.
Thanks!
I see two options here.
Create a function and parametrize it out. This is what Sethen Maleno's answer shows.
Make your function a more general function.
For example:
$(document).ready(function(){
// Apply this to every select element
$("select").change(function () {
// Dynamically build up the selector to show/hide
var secondMenuId = '#' + $(this).attr(id) + '_other_div'
if ($(this).val() == "Other" )
$(secondMenuId).css("visibility", "visible");
else
$(secondMenuId).css("visibility", "collapse");
});
});
Note that this approach requires discipline when you generate your HTML, and that the ids are assigned appropriately (which you seem to be doing since you mention using a standard naming convention).
This approach has the advantage that this is the only code you would have, and you wouldn't need to write lots of handlers.
Sethen's gives you a little more flexibility in that your ids wouldn't need to follow strict conventions (you could pass whatever you wanted as arguments), but does require you to write a function call to attach it to every item you want.
Both techniques are valid and have their time and place.
You can just use a single function with some code and call it multiple times (or once if you're using the same id or class)... Hence the purpose of functions: Reusable bits of code. Here's what it might look like.
$(function () { //shorthand for ready in jQuery
//set up your function
function dropDownOther(spotter, spotterDiv) { //function takes two args
$(spotter).change(function () {
if ($(this).val() == "Other") {
$(spotterDiv).css("visibility", "visible");
} else {
$(spotterDiv).css("visibility", "collapse");
}
});
}
dropDownOther("#spotter", "#spotter_other_div"); //call your function
dropDownOther("#otherSelector", "#otherSelectorTwo"); //call it again if necessary
});
I'm working on the address page for a shopping cart. There are 2 <select> boxes, one for Country, one for Region.
There are 6 standard countries available, or else the user has to select "Other Country". The <option> elements all have a numeric value - Other Country is 241. What I need to do is hide the Region <select> if the user selects Other Country, and also display a textarea.
You need to bind a function to the select list so that when it changes, your function decides if the div should be shown. Something like this (untested, hopefully syntactically close). Here's a live example.
$(document).ready( function() {
$('#YourSelectList').bind('change', function (e) {
if( $('#YourSelectList').val() == 241) {
$('#OtherDiv').show();
}
else{
$('#OtherDiv').hide();
}
});
});
It's the same principle as this question. You just need to connect to the change on the select , check the val() and hide()/show() the div.
In my opinion, you don't really need jQuery for this.
This simple JavaScript code will do the trick:
document.getElementById('country_id').onchange = function()
{
if (this.options[this.selectedIndex].value == 241) {
document.getElementById('region_id').style.display = 'block';
} else {
document.getElementById('region_id').style.display = 'none';
}
}
value works for most browsers, but yes, for older browsers you need select.options[select.selectedIndex].value. I updated my script.