jQuery - Change button text without refreshing page - javascript

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>

Related

jQuery show up two buttons from selectbox

I have this code and it works fine but not perfect. I don't know how to show up both buttons when I select options "two" and "three".
My code also seems too difficult, is a chance to write my code effectively or not? Thanks a lot.
function display() {
var selectBoxValues = $("#selectbox").val() || [];
if (selectBoxValues == '2') {
$('.select2').removeAttr('hidden', 'hidden');
}
if (selectBoxValues != '2') {
$(".select2").attr('hidden', 'hidden');
}
if (selectBoxValues == '3') {
$('.select3').removeAttr('hidden', 'hidden');
}
if (selectBoxValues != '3') {
$(".select3").attr('hidden', 'hidden');
}
}
$("#selectbox").change(display);
display();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectbox" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input hidden="hidden" type="button" class="button select2" value='Button 2' id="button">
<input hidden="hidden" type="button" class="button select3" value='Button 3' id="button">
jsfiddle
You should use the array in multiple selection and simply code as follows
function display() {
var selectBoxValues = $( "#selectbox" ).val() || [];
$(".button").attr('hidden','hidden'); //add hidden to all element
selectBoxValues.forEach(function(e){
$('.select'+e).removeAttr('hidden','hidden'); //remove hidden for selected elements
})
}
http://jsfiddle.net/hoa849p8/1/
Try this
function display() {
var selectBoxValues = $( "#selectbox" ).val() || [];
if (selectBoxValues.indexOf('2')>-1) {
$('.select2').removeAttr('hidden','hidden');
}
if (selectBoxValues.indexOf('2') == -1) {
$(".select2").attr('hidden','hidden');
}
if (selectBoxValues.indexOf('3')>-1) {
$('.select3').removeAttr('hidden','hidden');
}
if (selectBoxValues.indexOf('3')==-1) {
$(".select3").attr('hidden','hidden');
}
}
Working Fiddle
The issue you have is that the val() returned from the multiple select is an array, so by comparing an array to a string you will encounter issues when multiple options are selected.
To fix this you can use the indexOf() method to find the specific value in the array and show the relevant button using toggle(). Also note I've never seen hidden used as an attribute on an input element, and frankly I'm more amazed it works. I'd suggest you use CSS to hide/show the element instead. Finally, you should make the id attributes unique too, as sharing them between the buttons is invalid. Try this:
function display() {
var selectBoxValues = $("#selectbox").val() || [];
$('.select2').toggle(selectBoxValues.indexOf('2') != -1);
$('.select3').toggle(selectBoxValues.indexOf('3') != -1);
}
$("#selectbox").change(display).change();
.button { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectbox" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<input type="button" class="button select2" value="Button 2" id="button1">
<input type="button" class="button select3" value="Button 3" id="button2">
Thre problem with the code is selectBoxValues contains array of selected elements and we are comparing it only with first element. So we have to disable all the buttons first loop through array and remove hidden wherever necessary.
Here is the fiddle for it. http://jsfiddle.net/hoa849p8/4/
JS code is as below :
function display() {
var selectBoxValues = $( "#selectbox" ).val() || [];
console.log(selectBoxValues);
$('.button').attr('hidden','hidden');
$(selectBoxValues).each(function(i,item){
$('.select'+item).removeAttr('hidden');
});
}
$( "#selectbox" ).change( display );
display();
You can use the following as a little refactoring
http://jsfiddle.net/hoa849p8/2/
HTML
stays as yours
SCRIPT
function display() {
var selectBoxValues = $( "#selectbox" ).val() || [];
var buttons = $(".button");
buttons.attr("hidden", "hidden");
if (selectBoxValues == '2') {
$('.select2').removeAttr('hidden','hidden');
}
if (selectBoxValues == '3') {
$('.select3').removeAttr('hidden','hidden');
}
}
$( "#selectbox" ).change( display );

Replacing element with a previously saved element (select boxes)

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

Trigger the event when selected the same value in dropdown?

Issue: I have a dropdown with a list of years in it with nothing selected, the user selects "1976", I run a function. If the user clicks on the dropdown again and selects "1976" AGAIN, I want to run the function again.
$('select').on('change', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
});
Simple JS
---------
<html>
<head>
<script>
var prevIndex = "";
function onSelect()
{
var currIndex = document.getElementById("ddList").selectedIndex;
if( currIndex > 0 )
{
if( prevIndex != currIndex )
{
alert("Selected Index = " + currIndex);
prevIndex = currIndex;
}
else
{
prevIndex = "";
}
}
}
</script>
</head>
<body>
<select id="ddList" onClick="onSelect()">
<option value="0">Select Me</option>
<option value="1">List1</option>
<option value="2">List2</option>
<option value="3">List3</option>
</select>
</body>
</html>
This basic idea should work using jQuery using click event:
$('#yourselect').click(function() {
console.log("your function");
});
A simple if statement could prevent firing off the function when initially clicking the select element.
The closest functionality that you're seeking that I can think of is the following:
-HTML-
<select class="opt-evt">
<option value="" selected="selected"></option>
<option value="1976">1976</option>
</select>
-jQuery-
$(document).ready(function(){
$('.opt-evt').change(function(){
$(this).blur();
}).blur(function(){
console.log($(this).find('option:selected').val());
});
});
The caveat is that if the user selects '1976' again, the desired event only gets fired onBlur.
http://jsfiddle.net/4G9Jf/
mouseup event should do the trick:
$('select').mouseup(function(){
console.log("hue");
});
http://jsfiddle.net/5Fcgr/
note that this will be triggered twice when a new value is selected in the listbox. Once when opening the options, and once when selecting an option.
I have fixed as below,
<html>
<head>
<script>
function onSelect()
{
var dd = document.getElementById('ddList');
var txtTerms = document.getElementById('selValue');
var storeLstSlct = document.getElementById('checkIndx');
var slctdValue = '';
if(dd.selectedIndex == 0)
{
return false;
}else if(storeLstSlct.value == dd.options[dd.selectedIndex].value)
{
storeLstSlct.value = 'abcd';
return false;
}else
{
slctdValue = dd.options[dd.selectedIndex].value;
if(txtTerms.value != '')
txtTerms.value = txtTerms.value + ' , ' + slctdValue;
else
txtTerms.value = slctdValue;
storeLstSlct.value = slctdValue;
}
}
</script>
</head>
<body>
<select id='ddList' onclick='onSelect()'>
<option value='0'>Select Me</option>
<option value='One'>List1</option>
<option value='Two'>List2</option>
<option value='Three'>List3</option>
</select>
<input type='hidden' name='checkIndx' id='checkIndx' />
<input type='text' name='selValue' id='selValue' />
</body>
</html>

jQuery show/hide using select

I'm trying to apply a show/hide jQuery function to a html drop down box. I want to be able to hide one option and show another when an option from the drop down is selected. This jQuery works with a normal button but not the drop down.
<select style="margin-left:30px;">
<option value="" selected="selected">Please select a region</option>
<option id="uk_btn" value="1">UK</option>
<option id="usa_btn" value="2">USA</option>
</select>
<script>
$("#usa_btn").click(function(){
$("#usa_tbl").show();
$("#uk_tbl").hide();
});
</script>
<script>
$("#uk_btn").click(function(){
$("#uk_tbl").show();
$("#usa_tbl").hide();
});
</script>
You need to put the event for the select box like
$('select').change(function(){
var val = $(this + 'option:selected').attr('id');
if(val == 'uk_btn') {
$("#usa_tbl").hide();
$("#uk_tbl").show();
} elseif(val == 'usa_btn') {
$("#uk_tbl").hide();
$("#usa_tbl").show();
}
});
You can also check using value of the check box like
var val = $(this).val();
if(val == '1') {
$("#usa_tbl").hide();
$("#uk_tbl").show();
} elseif (val == '2') {
$("#uk_tbl").hide();
$("#usa_tbl").show();
}
You can do this:
// Cache the elements first
var $usa_tbl = $("#usa_tbl");
var $uk_tbl = $("#uk_tbl");
// Add a change event handler for the select element
$("#select_ID").change(function () {
if (this.value === '2') {
$usa_tbl.show();
$uk_tbl.hide();
} else if (this.value === '1') {
$uk_tbl.show();
$usa_tbl.hide();
} else {
$uk_tbl.hide();
$usa_tbl.hide();
}
});
where, select_ID is the ID of the select element.
Fiddle Demo
if you have no id on select then you can try
$('select').change(function(){
var val = $(this ).val();
if(val == 2) {
$("#usa_tbl").show();
$("#uk_tbl").hide();
} else {
$("#uk_tbl").show();
$("#usa_tbl").hide();
}
});
or you can do by id
<select id="select_id" style="margin-left:30px;">
now
$('#select_id').change(function(){
....same as previous
});
Root cause: There is no id matching for select in your js.
<select style="margin-left:30px;"> //id attribute is missing
instead use change event handler
<select style="margin-left:30px;" id="usa_btn">
JS:
$("#usa_btn").change(function(){
alert($(this).val()); // to get the value of selected option based on it
// add your condition
$("#usa_tbl").show();
$("#uk_tbl").hide();
});
<select id="country" style="margin-left:30px;">
then
$("#country").change(function(){
$('[id$="_tbl"]').hide();
$('#' + this.value.replace('_btn', '_tbl')) .show()
});

How to HIDE element based on IF statement when onClick is used

I need to be able to hide an image that appears when clicking on an option within a select field ONLY if the value="" (nothing inside quotes). If the value="some_url" inside the option, then I want the image to show.
I have used the following code to SHOW the image when an option is clicked. But when using onClick, it shows the image even if the option value="".
Here is the Javascript I'm using:
function showImage() {
document.getElementById('openimg').style.display = 'block';
Here is the html:
<select name="" >
<option value="url" onclick="showImage();">Some_option_1</option>
<option value="">Some_option_2</option>
<option value="">Some_option_3</option>
</select>
<a href='url_2'><img src='images/some_img.jpg' id='openimg' style='display:none'></a>
I only inserted one onClick command inside one option, just to show that it works. It seems I need an if statement to "show if" or "hide if" along with the onClick command within each option.
this is how I would do it:
<script type="text/javascript">
function showImage()
{
var choice = document.getElementById('myDropDown').value;
if(choice.length > 0)
{
document.getElementById('openimg').style.display = 'block';
}
else
{
document.getElementById('openimg').style.display = 'none';
}
}
</script>
<select id="myDropDown" onchange="showImage()">
<option value="url">Some_option_1</option>
<option value="">Some_option_2</option>
<option value="">Some_option_3</option>
</select>
<a href='url_2'><img src='images/some_img.jpg' id='openimg' style='display:none'></a>
Um, are you asking how to use an if or how to determine what is selected?
First of all, use onchange event in the dropdown.
This is the LONGHAND way of doing it for illustration purposes.
function onChange(){
var mySelect = document.getElementById("my-select");
var selectedValue = "";
for( var i = 0; i < mySelect.length;i++){
if( mySelect[i].selected)
selectedValue = mySelect[i].value;
}
if( selectedValue == "whatever")
{
//do something
}
if( selectedValue == "ugh")
// do something else
}

Categories

Resources