I've got some javascript to change a select box to a text box if an option is selected then change that text box back to a select box if the user hits delete/backspace to the point where they clear the text box.
http://jsfiddle.net/5e1stz46/6/
<select id='visit'>
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
$('#visit').on('change', function () {
if ((this.value) == 'Other') {
tmp = this;
$(this).replaceWith($('<input/>',{'type':'text','id':'visit'}));
}
});
$(document).keyup(function(e){
if( $('#visit').length ) {
if($('#visit').is(":focus") && $("#visit").val().length == 0){
$("#visit").replaceWith(tmp);
}
}
});
$('#visit').keyup(function(e){
if(e.keyCode == 46 || e.keyCode == 8) {
alert('box now empty');
}
});
When the text box changes back into a select box, all the events it had seem to be lost.
Should I be somehow reading the event listeners when the select box comes back or should I be saving the select box differently to start with?
The events got removed because you're removing associated Html element from the DOM. You can have both select and input and play with .hide() and .show to visualize the correct element and the events will work fine.
Another approach could be to use event delegation.
Changed Html:
<div id="wrapper">
<select id='visit'>
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
</div>
Changed JavaScript:
$('#wrapper').on('change', '#visit', function () {
if ((this.value) == 'Other') {
tmp = this;
$(this).replaceWith($('<input/>',{'type':'text','id':'visit'}));
}
});
[ ... ]
Rest of the code remains the same. Here is an updated JsFiddle Demo.
Once you remove the element from DOM, all its handlers are gone as well.
One solution would be to always keep the element, but just hide it from the user's view.
$('select[name=visit]').on('change', function () {
if (this.value == 'Other') {
$(this).addClass('hide');
$('input.hide').removeClass('hide');
}
});
$(document).keyup(function (e) {
var $elem = $('input[name=visit]');
if ($elem.length) {
if ($elem.is(":focus") && $elem.val().length == 0) {
$elem.addClass('hide');
$("select[name=visit]").removeClass('hide');
}
}
});
$('input[name=visit]').keyup(function (e) {
if (e.keyCode == 46 || e.keyCode == 8) {
alert('box now empty');
}
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="visit">
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
<input type="text" name="visit" class="hide" />
Also as there could be only one element with the unique id I always avoid using id attribute in dynamic HTML.
Second solution
Add a parent div wrapper and attached the handler to it as shown below:
$('#wrapper').on('change', '#visit', function () {
if ((this.value) == 'Other') {
tmp = this;
$(this).replaceWith($('<input/>', {
'type': 'text',
'id': 'visit'
}));
}
});
$(document).keyup(function(e){
if( $('#visit').length ) {
if($('#visit').is(":focus") && $("#visit").val().length == 0){
$("#visit").replaceWith(tmp);
}
}
});
$('#visit').keyup(function(e){
if(e.keyCode == 46 || e.keyCode == 8) {
alert('box now empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="wrapper">
<select id='visit'>
<option value='1'>option1</option>
<option value='2'>option2</option>
<option value='3'>option3</option>
<option value='Other'>Other</option>
</select>
</div>
JSFIDDLE
Related
I would like to make a jQuery check if a select field was changed. If it changes, set an alert message (has changed), if returned to default, set another alert message (default value).
$('select').on('change',function () {
var isDirty = false;
$('select').each(function () {
var $e = $(this);
if (!$e[0].options[$e[0].selectedIndex].defaultSelected) {
isDirty = true;
}
});
if(isDirty == true) {
alert("has changed");
} else {
alert("default value");
}
});
Please advise if this is the proper way.
You don't need inner each loop. Plus $(this)[0] can be optimised to just this:
$('select').on('change', function () {
var isDirty = !this.options[this.selectedIndex].defaultSelected;
if (isDirty) {
alert("has changed");
} else {
alert("default value");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="">
<option value="1">Label 1</option>
<option value="2" selected>Label 2</option>
<option value="3">Label 3</option>
<option value="4">Label 4</option>
</select>
I would do something like:
HTML:
<select data-default="one" id="the-select">
<option>one</option>
<option>two</option>
</select>
Javascript:
$('#the-select').change(function() {
var changed = $(this).val() != $(this).data('default');
alert(changed ? 'changed' : 'not changed');
});
I have a function to check if the value meet the requirement, it is working fine so I have another drop-down(select) to validate with same condition but the drop-down values different I am only checking the blank selection.
Goal:
any way to improve the JS or combine them correctly.
Many thanks in advance
// for 1st drop down
function checkPrimeSelectChangeValue() {
var selObj = document.getElementById("dropdown1");
var selValue = selObj.options[selObj.selectedIndex].value;
if (selValue == "") { // if blank is selected add css for validation
$("#dropdown1").attr('disabled', 'disabled');
$("#dropdown1").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown1"); // remover error
}
return;
}
// 2nd dropdown like below
function checkSecondSelectChangeValue() {
var selObj2 = document.getElementById("dropdown2");
var selValue2 = selObj.options[selObj.selectedIndex].value;
if (selValue2 == "") { // if blank is selected add css for validation
$("#dropdown2").attr('disabled', 'disabled');
$("#dropdown2").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown2"); // remover error
}
return;
}
// Can I do this or Any ipmorvent can be done to this
function checkCombinedSelectChangeValue() {
var selObj = document.getElementById("dropdown1");
var selObj2 = document.getElementById("dropdown2");
var selValue = selObj.options[selObj.selectedIndex].value;
var selValue2 = selObj.options[selObj.selectedIndex].value;
if (selValue == "") { // if blank is selected add css for validation
$("#dropdown1").attr('disabled', 'disabled');
$("#dropdown1").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown1"); // remover error
}
return;
if (selValue2 == "") { // if blank is selected add css for validation
$("#dropdown2").attr('disabled', 'disabled');
$("#dropdown2").addClass("text-error");
} else {
$("#btnUpdateForm").removeAttr('disabled'); // disabled button
removeError("#dropdown2"); // remover error
}
return;
}
<p>1st dropdown1 </p>
<select name="test" id="select">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
<br>
<p>2nd dropdown1 </p>
<select name="test" id="select2">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
I optimized your function a little, assuming it's supposed to run when your select changes. I also assume that you want to add the disabled property to your #btnUpdateForm since that isnt really clear with the code you provided.
First add the disabled property to your Update button like this:
<button id="btnUpdateForm" disabled>Update</button>
HTML:
<p>1st dropdown1 </p>
<select class="dropdown" name="test" id="select">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
<br>
<p>2nd dropdown1 </p>
<select class="dropdown" name="test" id="select2">
<option value="">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
</select>
JQuery:
$('.dropdown').change(function() {
var val1 = $('#select').val();
var val2 = $('#select2').val();
if (val1 == '' || val2 == '') {
$('#btnUpdateForm').prop('disabled', true);
if (val1 == '') {
$('#dropdown1').addClass('text-error');
if (val2 !== '') {
$('#dropdown2').removeClass('text-error');
}
}
else if (val2 == '') {
$('#dropdown2').addClass('text-error');
if (val1 !== '') {
$('#dropdown1').removeClass('text-error');
}
}
}
else {
$('#btnUpdateForm').prop('disabled', false);
$('#dropdown1').removeClass('text-error');
$('#dropdown2').removeClass('text-error');
}
});
Basically now the Error will show up for each Dropdown with value="" and the button will only be enabled when both Dropdown's value isn't 0.
I want to change my button text as below, I have two select option, draft and publish. When I select to the draft option, button text must be change. But I can't change it without refreshing page. How can I do that ?
<body>
<button id="button" value=""></button>
<select name="select" id="draftOrPublish">
<option value="0">Draft</option>
<option value="1">Publish</option>
</select>
</body>
<script>
var draftOrPublish = $('select#draftOrPublish').val();
if (draftOrPublish == 0) {
$('button#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('button#button').text('Publish')
}
</script>
You have to put the code inside $(document).ready and $( 'select#draftOrPublish' ).change
$(document).ready - A page can't be manipulated safely until the document is "ready."
$( 'select#draftOrPublish' ).change - Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
$(document).ready(function(){
$( 'select#draftOrPublish' ).change(function(){
var draftOrPublish = $('select#draftOrPublish').val();
if (draftOrPublish == 0) {
$('button#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('button#button').text('Publish')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="button" value=""></button>
<select name="select" id="draftOrPublish">
<option value="0">Draft</option>
<option value="1">Publish</option>
</select>
You need to bring this into a function in order to assess whether or not the value of the select has changed. This is called an event, and you need an event listener attached to your <select> tag so that you can apply your event handler to change the text of the button. jQuery has a .change() function you can use to listen to the <select> tag
var draftOrPublish = $('#draftOrPublish').val();
if (draftOrPublish == 0) {
$('#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('#button').text('Publish')
}
$('#draftOrPublish').change(function () {
var draftOrPublish = $('#draftOrPublish').val();
console.log(draftOrPublish)
if (draftOrPublish == 0) {
$('#button').text('Save as Draft')
} else if (draftOrPublish == 1) {
$('#button').text('Publish')
}
})
You can use change() in jQuery to change text and value dynamically without page load.
$('#draftPublish').change(function () {
var draftPublish = $('#draftPublish').val();
if (draftPublish === "0") {
$('#btn').text('Save as Draft');
$('#btn').val('draft');
} else if (draftPublish === "1") {
$('#btn').text('Publish');
$('#btn').val('publish');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn" value="draft">Save as Draft</button>
<select name="select" id="draftPublish">
<option value="0">Draft</option>
<option value="1">Publish</option>
</select>
I am building a web application where you can mark TV shows as "Want to Watch", "Currently Watching", "Finished Watching", or "Stopped Watching." There is a dropdown to select between these. If "Currently Watching" is selected, two more dropdowns should also be displayed for a user to enter their last watched season and episode. However, I am having trouble getting the jQuery to work properly
HTML
<select name="updateTvStatus" class="form-control" id="updateTvStatus">
<option value="4" selected>Want to Watch</option>
<option value="1">Currently Watching</option>
<option value="2">Finished Watching</option>
<option value="3">Stopped Watching</option>
</select>
<div id="last-watched" class="hidden">
<select name="updateLastSeason" class="form-control" id="updateLastSeason">
<option value="0">Select Season:</option>
<option value="1">Season 1</option>
<option value="2">...</option>
</select>
<select name="updateLastEpisode" class="form-control" id="updateLastEpisode">
<option value="0">Select Episode:</option>
<option value="1">Episode 1</option>
<option value="2">...</option>
</select>
</div> <!-- /last-watched -->
jQuery
$(document).ready(function() {
$("#updateTvStatus").change(function() {
var TVstatus = $("#updateTvStatus").val();
var ishidden = $('#last-watched').hasClass("hidden");
if (TVstatus == 1 && ishidden == TRUE) {
$('#last-watched').removeClass("hidden");
} elseif (TVstatus != 1 && ishidden == FALSE) {
$('#last-watched').addClass("hidden");
}
});
});
else if (elseif) - syntax error.
Since JS is case sensitive, you'll ve to change TRUE/FALSE to true/false.
You've specified class selector instead of id selector. Pls change $('.last-watched') to $('#last-watched').
(And you may use === instead of == for strict comparison).
So, a completed code ll look like this to work:
$(document).ready(function() {
$("#updateTvStatus").change(function() {
var TVstatus = $("#updateTvStatus").val();
var ishidden = $('#last-watched').hasClass("hidden");
if (TVstatus == 1 && ishidden == true) {
$('#last-watched').removeClass("hidden");
} else if (TVstatus != 1 && ishidden == false) {
$('#last-watched').addClass("hidden");
}
});
});
I don't know what exactly you are looking for . But this is what you want for :
$(document).ready(function() {
$('#last-watched').hide();
$("#updateTvStatus").change(function() {
var TVstatus = $("#updateTvStatus").val();
if(TVstatus == 1){
$('#last-watched').show();
}else {
$('#last-watched').hide();
}
});
});
</script>
I have HTML:
<select class="form" id="select" name="select">
<option>number1</option>
<option>number2</option>
</select>
<select name="organisation" class="form" id="cent" required>
<option value="1">UK</option>
<option value="2">SPAIN</option>
</select>
And another <select>:
<select class="form" id="ssip" name="organisation">
<option value="47" >US</option>
<option value="48">UKRAINE</option>
</select>
JQuery to show on 1 - first select on 2 - second
$(document).ready(function() {
$("#select").each(function () {
if (this.value == "1") {
$('#cent').show();
$('#ssip').hide();
}
if (this.value == "2") {
$('#cent').hide();
$('#ssip').show();
}
});
});
The problem is that when i choose option number1 appears first select with values 1 and 2 but when i select UK with value 1 and click submit it's sending value 47 , of second select's first option..
Try disabling the opposite select when toggling the selects. A control on a form will still be submitted if its display is set to none, however if the control is disabled it will not be submitted with the form.
$(document).ready(function() {
$("select").change(function () {
if (this.value == "number1") {
$('#cent').show().prop("disabled", false);
$('#ssip').hide().prop("disabled", true);
}
if (this.value == "number2") {
$('#cent').hide().prop("disabled", true);
$('#ssip').show().prop("disabled", false);
}
});
});
JS Fiddle: http://jsfiddle.net/bTJsH/
You are trying to loop one select box..
$("#select").each(function () {
There can be only one element with id "select". You should check like:
if ($("#select").value() == "1") { ..
And you don't even have values in your first select options..
i might suggest something like this
$('#select').on('change', function() {
var selected = this.selectedIndex;
$('.orgs').hide();
switch(selected) {
case 1:
$('#ssip').show();
break;
case 2:
$('#cent').show();
break;
}
});
here is an working example http://jsfiddle.net/pixelchemist/7ZGwy/