jQuery Mobile Show/Hide Form input based on select field - javascript

I have the following form fields on my jQuery Mobile page. I want to initially hide the element, and then have it .show() if the user selects the option with value="Other"
Here's my HTML:
<div data-role="fieldcontain" class="no-field-separator">
<select name="plan_height" id="plan_height" data-native-menu="false">
<option>Plan Height</option>
<option value="Standard 6foot 2inch">Standard 6'2"</option>
<option value="Other">Specify in Notes</option>
</select>
</div>
<div id="specify_plan_height_box" style="display:none;">
<div data-role="fieldcontain" class="ui-hide-label no-field-separator">
<label for="specify_plan_height">Specify Plan Height</label>
<input type="text" id="specify_plan_height" name="specify_plan_height" placeholder="Specify Plan Height" maxlength="50" />
</div>
</div>
and here's my JS INSIDE the page:
// $( '#machine-guarding-page' ).live( 'pageinit',function(event) {
$( document ).bind( "pageinit", function( event, data ) {
$('#plan_height').change(function() {
var planHeightVal = $("#plan_height option:selected").val();
var sphb = $("#specify_plan_height_box");
sphb.hide();
if (planHeightVal == "Other") {
sphb.show();
}
});
});
});
It works fine here in this working example. Do I need to have something other than $(".page").live('pageinit', function() {
at the top of my JS code to make it work after the page loads? It works fine in the example link above, but not on my jQuery Mobile site.

Does this work for you:
http://jsfiddle.net/Qe6G4/1/
http://jsfiddle.net/Qe6G4/2/ (optimized)
http://jsfiddle.net/Qe6G4/3/ (with another input)

Related

Hide virtual keyboard after selecting value on Select2 v3

I'm using select2 v.3.4.5 solely for my project. Currently, when viewing on mobile, the keyboard does not close after it open and value selected, I would like to close it thought. I would like open only when user focus on it and type something.
$(document).ready(function() {
$('#Salutation,#Gender').select2()
.on('change select-open', function(e) {
setTimeout(function() {
$('.select2-input').blur();
}, 500);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-4 col-xs-offset-4">
<h3>Application Form</h3>
<form class="form" action="/action_page.php">
<div class="form-group">
<label for="GivenName">Given Name:</label>
<input class="form-control" type="text" id="GivenName">
</div>
<div class="form-group">
<label for="Surname">Surname:</label>
<input class="form-control" type="text" id="Surname">
</div>
<div class="form-group">
<label for="Salutation">Salutation:</label>
<select class="" name="" id="Salutation">
<option value="Mrs">Mrs</option>
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
</select>
</div>
<div class="form-group">
<label for="Gender">Gender:</label>
<select class="" name="" id="Gender">
<option value="Female">Female</option>
<option value="Male">Male</option>
<option value="Transgender">Transgender</option>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
As this js
$('#Salutation,#Gender').select2()
.on('change select2-open',function(e){
setTimeout(function(){
$('.select2-input').blur();
}, 500);
});
I set input-search box to blur already but keyboard does not close.
How can I do to archive this purpose? Please kindly help. Thanks.
PS: Understandably, select2 v4 fixed this bug, yet I could not upgrade my select2 version since my project is solely depend on v3.*
Ensuring the search box does not autofocus
There is no way to do this well in Select2 - whenever you try to call the blur() function on this input, it just refocuses it.
However, by listening on the open event, we can replace the search box with our own one, that does not autofocus. Only the currently active search box has the class select2-focused, so we use that to find it, and then create a new search box (with the same select2-input class so it retains the same look and feel), and then re-implement the search feature ourselves, finally inserting that into the DOM, and removing the old search box.
Not showing the keyboard after closing the selection popup
Select2 seems to try and implement its own blur() event in a very weird way (see here).
So, rather than try and use that, take advantage of CSS selectors. The :focus selector in CSS selects anything that has focus. Since Select2 doesn't actually add any new DOM elements (i.e. once in the HTML, it becomes standard <div> elements, <input> elements, etc), we can find the one that has focus, and successfully call blur on it.
Therefore, by calling $(":focus").blur(), we find the DOM element that currently has focus, and we blur it.
Also, by using select2-close as our event, rather than change, the keyboard won't open even if the user doesn't select an item, but instead clicks outside of it.
I have tested it, and it does work for me on an iPad running iOS 11. Here is the final, working code:
$(document).ready(function() {
$("#Salutation,#Gender").select2().on("select2-open",()=>{
let oldSearchBox = $(".select2-focused")[0]; //Get the current search box
let parent = oldSearchBox.parentNode; //The parent of the search box (i.e. the element that holds it)
let search = document.createElement("input"); //Create a new input box
search.classList.add("select2-input"); //Make it look like the old one
search.addEventListener("keyup", ()=>{ //Whenever someone releases a key, filter the results
let results = parent.parentNode.getElementsByClassName("select2-result"); //Get all of the select box options
let query = search.value.toLowerCase(); //Get what the user has typed (in lower case so search is case-insensitive)
for (let result of results) { //Loop through all of the select box options
let resultText = result.children[0].childNodes[1].nodeValue.toLowerCase(); //Get the text for that option (also in lower case)
result.style.display = (resultText.indexOf(query)==-1) ? "none" : "block"; //If the result text contains the search, it is displayed, otherwise it is hidden
}
})
parent.appendChild(search); //Add the new search box to the page
oldSearchBox.remove(); //Remove the old one
});
$("#Salutation,#Gender").select2().on("select2-close",()=>{
setTimeout(()=>{
$(":focus").blur();
}, 50);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-4 col-xs-offset-4">
<h3>Application Form</h3>
<form class="form" action="/action_page.php">
<div class="form-group">
<label for="GivenName">Given Name:</label>
<input class="form-control" type="text" id="GivenName">
</div>
<div class="form-group">
<label for="Surname">Surname:</label>
<input class="form-control" type="text" id="Surname">
</div>
<div class="form-group">
<label for="Salutation">Salutation:</label>
<select class="" name="" id="Salutation">
<option value="Mrs">Mrs</option>
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
</select>
</div>
<div class="form-group">
<label for="Gender">Gender:</label>
<select class="" name="" id="Gender">
<option value="Female">Female</option>
<option value="Male">Male</option>
<option value="Transgender">Transgender</option>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
I have an alternative work around that I've been using for about a week now. So far it seems to work well on all android and ios devices I've tried. I use this on select2 instances that have 'multiple' set to false (i.e. 'single' type). In this case, I want the user to make a single selection, and the the keyboard should disappear.
In short, during the select2-close event you set a flag that indicates that you want to disable any focus event the select2-focusser receives. When the focus event is triggered, you check if the flag is set and if so you simply move the focus to another target. I add the flag as a data property and I reset this flag after a second using a setTimeOut.
This works because the select2 close handler is split into 2 parts, and the 'select2-close' event is triggered at the end of part 1 (and before part 2). Part 1 is the 'abstract' close handler, which actually closes the selection dialog, and sets the control's value. Part 2 is the 'single' close handler, which really just causes the select2 to refocus on itself (which is the problem!).
For me, I added a '.focus-bait' class to one of my nav bar buttons, and I use this to divert focus during the focusser's focus event execution. If you have issues getting this refocus step to work, try a different element (I had a problem getting it to work on a button I had made for the purpose of focusing on. I'm still not sure why, but I didn't investigate more as my nav button solution worked perfectly for my needs).
$('body').on('focus','.select2-focusser', function(e) {
let isDisabled = $(this).parent().first().data("disable-focus");
if (isDisabled) {
console.log('Focusser: focus event aborted');
$('.focus-bait').focus();
}
});
//select2_focus_ctrl is a class that I add to any select2 container
//that I wish to use this focus logic e.g. add it to #Salutation,#Gender
$('body').on('select2-close','select2_focus_ctrl', function(e) {
console.log('Focusser: disabling focus event');
if ($(this).data('select2').opts.multiple != true) {
$(this).prev().data("disable-focus",true);
setTimeout(function() {
console.log('Focusser: enabling focusser');
$(this).prev().data("disable-focus",false);
}, 1000);
}
});
Here is a full code snippet. While writing it I noticed that if the select2 container is sourced from a 'select' element, the 'multiple' property does not exist (mine used a 'div'), so I've changed one line of code: .opts.multiple != true (instead of == false).
$(document).ready(function() {
$('#Salutation').select2(
);
$('body').on('focus','.select2-focusser', function(e) {
let isDisabled = $(this).parent().first().data("disable-focus");
if (isDisabled) {
console.log('Focusser: focus event aborted');
$('.focus-bait').focus();
}
});
$('body').on('select2-close','.select2_focus_ctrl', function(e) {
console.log('Focusser: disabling focus event');
if ($(this).data('select2').opts.multiple != true) {
$(this).prev().data("disable-focus",true);
setTimeout(function() {
console.log('Focusser: enabling focusser');
$(this).prev().data("disable-focus",false);
}, 1000);
}
});
$('body').on('change','#Salutation', function(e) {
let theVal = $('#Salutation').select2("val");
$('#currentVal').val(theVal);
});
});
body {
background: #dddddd;
padding: 20px;
font-family: Helvetica;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
cursor: pointer;
}
button:focus {
background: #fff;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<button type="button" class="focus-bait">
Just the bait!
</button>
<br>
<div>
<input id="currentVal" style="height:20px;width:150px"/>
</div>
<br><br>
<select class="select2_focus_ctrl" id="Salutation" style="width:200px;">
<option value="Mrs">Mrs</option>
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Esquire">Esquire</option>
<option value="Other Options">Other Options</option>
<option value="Just for interest">Interesting longer item</option>
</select>

Show Hidden Form Field with Jquery

I seem to be having an issue with Jquery not displaying a hidden DIV after a selected form value is chosen. When a user clicks yes, I want the hidden div to then be revealed. Am I missing something? You can take a look here https://jsfiddle.net/73merxk9/
Javascript
<script>
$(document).ready(function() {
$('#permit').on('permit', function() {
$("#hiddenform").toggle($(this).val() == 'Yes');
}).trigger('permit');
});
</script>
Form
<div>
<label for="permit">Permit</label>
<select id="permit" name="permit">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div id="hiddenform">
<div>
<label for="permit_submitted">Permit Submitted</label>
<input placeholder="Permit Input Here..." name="job_number" type="text" id="job_number">
</div>
</div>
There is no such event "permit". You need to listen onchange event instead. Then you need to compare select value with "1" because Yes is a label, not value:
$(document).ready(function () {
$('#permit').on('change', function () {
$("#hiddenform").toggle($(this).val() == '1');
}).trigger('change');
});
Demo: https://jsfiddle.net/73merxk9/1/

Cannot select a dropdown item in jQuery to make it display a hidden textbox

I am trying to get a paragraph with some text and a textbox to show up when a certain option in the dropdown select menu on my form is clicked. Similar code worked for radio buttons, but doesn't seem to in this case. I would really appreciate any help that I can get on this. jsfiddle
HTML:
<select name="select1">
<option value="doctor" id="doctor1">Doctor</option>
<option value="nurse" id="nurse1">Nurse</option>
<option value="other" id="other1">Other</option>
</select>
<div class="otherprof">
<p>Please list your profession:
<input type="text" name="otherproftext" id="otherproftext" maxlength="20">
</p>
</div>
jQuery:
$(document).ready(function () {
$(".otherprof").hide();
$("#other1").click(function () {
$(".otherprof").show();
});
$("#doctor1").click(function () {
$(".otherprof").hide();
});
$("#nurse1").click(function () {
$(".otherprof").hide();
});
});
Idea is that the textbox stays hidden until users click on "Other" in the dropdown, which in turn is supposed to display the textbox immediately.
You need to use the onchange event on the select, not click on the options.
$("[name='select1']").on("change", function(){ //listen for change event on the select
$(".otherprof").toggle(this.value==="other"); //toggle show/hide based on selected value
}).change(); //trigger the change event so default value is checked
JSFiddle
Add the style attribute to the div otherprof and it will be hidden initially
<select name="select1">
<option value="doctor" id="doctor1">Doctor</option>
<option value="nurse" id="nurse1">Nurse</option>
<option value="other" id="other1">Other</option>
</select>
<div class="otherprof" style="display:none;">
<p>Please list your profession:
<input type="text" name="otherproftext" id="otherproftext" maxlength="20">
</p>
</div>

Disable SUBMIT button until select box choices

I have a small form.
Two select box elements and a submit button.
The select box elements collectively when selections are chosen, fire off an ajax request.
What I want to do is, disable the submit button UNTIL user has made selections from the select drop downs.
They must make a selection from BOTH select drop downs, before the Submit button is enabled.
I dont mind if the submit button is hidden until selections made.
Brief Code:
<form id="ad_form" method="post" action="">
<p>
<select id="ad_type" name="ad_type">
<option value="" selected="selected">Select premium ad type</option>
<option value="<?php echo TYPE_USER;?>">Featured Agent</option>
<option value="<?php echo TYPE_LISTING;?>">Featured Listing</option>
</select>
<label for="ad_type" class="labelStrong">Advertising Type</label>
</p>
<p>
<select id="ad_duration" name="ad_duration">
<option value="" selected="selected">Select premium ad duration</option>
<option value="weekly">Weekly</option>
<option value="fortnightly">Fortnightly</option>
<option value="monthly">Monthy</option>
</select>
<label for="ad_duration" class="labelStrong">Advertising Duration</label>
</p>
<p>
<div id="calender">
</div>
</p>
<p>
<input type="submit" name="submit" value="Submit" id="submitorder" />
</p>
</form>
Here's a demo that seems to do what you want:
http://jsfiddle.net/Yr59d/
That javascript code would go in a $(document).ready() block
$(function() {
$("#submitorder").css("visibility", "hidden");
$("#ad_form select").bind("change", function() {
if ($("#ad_type").val().length > 0 && $("#ad_duration").val().length > 0) {
$("#submitorder").css("visibility", "visible");
} else {
$("#submitorder").css("visibility", "hidden");
}
});
});
If you give all your selects a common class name (like 'required') , you can do something like this:
$('select.required').change(function() {
var total = $('select.required').length;
var selected = $('select.required option:selected').length;
$('#submitorder').attr('disabled', (selected == total));
});
This is not tested code. This documentation might help. This jquery discussion might help too.
Gah, I'll have to agree with Kon on this one - fix-now-worry-about-it-later answers have their place but an elegant solution that is simple at the same time has to be the way to go.
My solution: (with credit from a thread at: JQuery Enable / Disable Submit Button in IE7)
$('select.required').change(function() {
var total = = $('select.required').length;
var selected = $('#ad_form').find("select.required option[value!='':selected").length;
$('#submitorder').prop('disabled', (selected != total));
});
Incidentally, thanks ctcherry for demoing the code on the JSFiddle site - I've not seen that before and will make use of it in the future!
Use listeners on both select buttons for change and check whether the other is also set. If set, enable the submit button.

Hide elements using jquery based on option select

I have two forms and a selector.
This is my code --
<select>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<form id="pp">
<input type="text">
</form>
<form id="cc">
<input type="text">
</form>
Now if option 1 is selected i want to hide form CC. if 2 hide form PP.
How do i do it with js or jquery? thanks
Try this (using jQuery):
$("select").bind("change", function() {
if ($(this).val() == "1") {
$("#pp").show();
$("#cc").hide();
}
else if ($(this).val() == "2") {
$("#pp").hide();
$("#cc").show();
}
});
Additionally, you could hide both forms using .hide() as shown above before the user selects any option.
bind is attaching an event handler to the "change" event of the select box. This is fired when the user changes what option is selected.
Inside the handler, val is used to determine the value of the currently selected option.
show() and hide() are used on the correct forms, depending on which option was selected.
Working example: http://jsfiddle.net/andrewwhitaker/faqZg/
<script>
function Hide(val)
{
if(val==1)
{
document.getElementById('cc').style.display='none';
document.getElementById('pp').style.display='inline';
}
if(val==2)
{
document.getElementById('pp').style.display='none';
document.getElementById('cc').style.display='inline';
}
}
</script>
<select onchange="Hide(this.value);">
<option value="">Please Select</option>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<div id="pp">
<input type="text">
</div>
<div id="cc">
<input type="text">
</div>

Categories

Resources