Change button class and value for each click - javascript

I just made a timer with control, but in the control button i need some help.
Initially there have a button with START value. have to change the class and value to "STOP" for the 1st click and for the 2nd click change the class & value to "RESUME".
DEFAULT. <input class="start" type="button" value="START" />
1st click. <input class="stop" type="button" value="STOP" />
2nd click. <input class="resume" type="button" value="RESUME" />
3rd click. <input class="stop" type="button" value="STOP" />
4th click. <input class="resume" type="button" value="RESUME" />
Can you help me in this? and forgive my bad English.
FYI: i am using JQUERY MOBILE.

I haven't worked in JQuery mobile but this should be the way
JQuery
$(document).ready(function(){
$('input').click(function(){
if($(this).hasClass("start")){
$(this).removeClass("start");
$(this).addClass("stop");
$(this).val("STOP");
}else if($(this).hasClass("resume")){
$(this).removeClass("resume");
$(this).addClass("stop");
$(this).val("STOP");
}else if($(this).hasClass("stop")){
$(this).removeClass("stop");
$(this).addClass("resume");
$(this).val("RESUME");
}
});
})
for reference http://jsfiddle.net/zGMWR/1/
hope it helps
P.S. please put specific selector in jquery for your button.

Your initial value 'start' is irrelevant here as it only appears the very first time. So a simpler solution would be:
$(':button').on('click', function(){
$(this).removeClass('start stop resume');
if (this.value !== 'STOP') {
this.value = 'STOP';
$(this).addClass('stop');
} else {
this.value = 'RESUME';
$(this).addClass('resume');
}
});
An even shorter version would be:
$(':button').on('click', function(){
this.value = this.value !== 'STOP' ? 'STOP' : 'RESUME';
$(this).removeClass('start stop resume')
.addClass(this.value.toLowerCase());
});
Side info: answer from PSK: 376 Bytes; first answer here: 223 Bytes; second answer: 174 Bytes
Of Course you can wrap it in a $(document).ready(function(){ function if necessary
See http://jsfiddle.net/zGMWR/2/ and http://jsfiddle.net/zGMWR/3/ how it works
For a more specific selector and using event delegation you could use:
$('form').on('click', ':button', function(){...
or give the button an even more specific class name such as play-button

Related

How to change a global variable inside jQuery selectors?

I'm developing a website, which is using jQuery.Inside this code I need to change the value of a variable inside a Jquery selector and get the changed value after it.Is it possible to do that?How can I achieve this?If possible, could show me a snippet/example code?
I've tried declaring the variable global, but without success too.
var index;
$(document).ready( function(){
$("#myButton1").click(function(){ //selector number 1
index = 1;
});
$("#myButton2").click(function(){//selector number 2
index = 2;
});
//after, i need the value of the index for another selector
//look this next selector is fired at the same time as the previous one!
$("button[id^=myButton"+index+"]").click( function(){ //selector number 3
...
}
}
How can I make the selector number 1 or 2 fire after the selector number 3?Is it possible?
Javascript executes code asynchronously. In other words, whole code executes at the "same time." So first, it will execute var index;. Since the jQuery .click is waiting for you to click the button, it will skip both of the .click functions and move on to the alert. Since index is undefined, it will say index=undefined. To fix that, move the alert's inside the .click function so that the alert will execute after you click the button.
var index;
$("#button1").click(function() {
index = 1;
alert("index = " + index);
});
$("#button2").click(function() {
index = 2;
alert("index = " + index);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1"></button>
<button id="button2"></button>
Or you could do it this way:
var index = 0;
$("#button1").click(function() {
index = 1;
});
$("#button2").click(function() {
index = 2;
});
setTimeout(function() {
alert("index = " + index);
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1"></button>
<button id="button2"></button>
The above method basically executes the alert after 5 seconds, so you can change the value of index as many times as you want in those 5 seconds. The default value is 0, but if you click the first button within those 5 seconds, the value of index changes to 1. Same for the second button.
The things that happen when you click one of the buttons are those you define inside the click-handler function (see here):
$("#button1").click(function(){
window.index = 1; // only this line!!!
});
Your call to alert() resides inside the ready-funtion and is therefore only called when the page is loaded. You need to put the alert inside the click handlers to call it "on click". Doing so, all three versions should work. Should look like this:
$("#button1").click(function(){
index = 1;
alert(index);
});
After your edit:
Same thing here: the selector string after you comment is created at the time of the page load, before any button is clicked. and never again after that.
At that moment, it evaluates to "button[id^=myButtonundefined]" because index has no defined value yet. T## is function therfore will be executed whenever you click a button whose ID starts with myButtonundefined - probably never.
Everything you want to achieve, for which you need the value of index you need to execute inside the click-handler function. e.g.:
$(document).ready( function(){
$("#button1").click(function(){
$("button[id^=myButton1]").click( function(){
...
});
});
$("#button2").click(function(){
$("button[id^=myButton2]").click( function(){
...
});
});
}
or you could try the following approach, which installs a click-handler on all myButton...'s and therein checks if the corresponding button... has been clicked before:
var index;
$(document).ready( function(){
$("#button1").click(function(){
index = 1;
});
$("#button2").click(function(){
index = 2;
});
//after, i need the value of the index for another selector:
$("button[id^=myButton]").click( function(){
if (this.id == 'myButton'+index) {
...
}
}
}
How to change a global variable inside jQuery selectors?
Don't use a global variable in this instance. You have a chance of a variable collision with any other code (jQuery or any other script you use). You can simply place index inside your document ready and use it in your example code and it will work without any chance of collision.
$(document).ready( function(){
var index;
$("#button1").click(function(){
index = 1;
});
$("#button2").click(function(){
index = 2;
});
//after, i need the value of the index for another selector:
$("button[id^=myButton"+index+"]").click( function(){
});
$('.js-getcurrentvalue').on('click', function() {
$('#currentvalue').val(index);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-getcurrentvalue" value="Get Current Value of Index"/><input type="text" id="currentvalue" /><br/>
<input type="button" id="button1" value="button1" /><br/>
<input type="button" id="button2" value="button1" /><br/>
But at the same time, the selector $("button[id^=myButton"+index+"]").click( function(){ }); fires.So, both are executed at the same time.I need that the second selector execute always after the first selector.Do u know how can I accomplish this?
This is not the original question you asked. Please read what an XY Problem is so your future questions can be answer correctly.
Highly recommended reading: Decouple your HTML, CSS and Javascript.
First we need to understand that each of these statements that attach an event handler onto an element all run before the event handler can be executed. So in my previous example the following events are registered:
$("#button1").click()
$("#button2").click()
$("button[id^=myButton]").click();
$('.js-getcurrentvalue').on('click')
You'll notice that I've done what any compiler would do and reduce the variable into it's actual value. At the time the event handler is attached, index has no value. Since this isn't what you want, you could write it like:
$("button").click(function() {
var $this = $(this);
var id = $this.prop(id);
if ($this.is("[id^=myButton"+index+"]") {
// do something as index changes
}
});
But it's really ugly and introduces an abstraction of a value to used to compare. It's also very tightly coupled, that is we have to place an event on any object we want to change index and we have to write more code for each button. Yikes. Instead we can use classes and the data-attribute with data() to simplify and make this more robust.
$(document).ready( function(){
var selector;
$(".js-enable-button").on('click', function(){
selector = $(this).data('selector');
});
$('.js-enable-me').on('click', function() {
var $this = $(this);
if ($this.is(selector)) {
alert($this.val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button1" />
<input type="button" class="js-enable-me" id="button1" value="Am I working?" /><br/>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button2" />
<input type="button" class="js-enable-me" id="button2" value="Or am I working?" /><br/>
Now the code is not limited to an Id. It's also not limited to a single selector. You could go crazy and just by adding only html the following continues to work for all elements. Notice I've added no additional code.
$(document).ready( function(){
var selector;
$(".js-enable-button").on('click', function(){
selector = $(this).data('selector');
});
$('.js-enable-me').on('click', function() {
var $this = $(this);
if ($this.is(selector)) {
alert($this.val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button1" />
<input type="button" class="js-enable-me" id="button1" value="Am I working?" /><br/>
<input type="button" class="js-enable-button" value="Enable button -->" data-selector="#button2" />
<input type="button" class="js-enable-me" id="button2" value="Or am I working?" /><br/>
<br/>
<input type="button" class="js-enable-button" value="I enable the three below me using id" data-selector="#id1,#id2,#id3" /></br>
<input type="button" class="js-enable-me" id="id1" value="id1" /><br/>
<input type="button" class="js-enable-me" id="id2" value="id2" /><br/>
<input type="button" class="js-enable-me" id="id3" value="id3" /><br/>
<br/>
<input type="button" class="js-enable-button" value="I enable the three below me using a class" data-selector=".enable" /></br>
<input type="button" class="js-enable-me enable" value="I'm .enable 1" /><br/>
<input type="button" class="js-enable-me enable" value="I'm .enable 2" /><br/>
<input type="button" class="js-enable-me enable" value="I'm .enable 3" /><br/>

JavaScript generated code and screen readers

I'm asking you to help me out, I'm totally stuck with this problem.
I want to make possible my code to be navigated through keyboard and adoptable to screen reader devices. But I have several issues.
This is my code in JS:
function changeText()
{
document.getElementById('div1').innerHTML = '<input id="btn2" type="button" onclick="changeText2()" value="Change Text2" />';
document.getElementById('btn1').setAttribute("aria-hidden",true);
document.getElementById('div1').focus();
}
function changeText2()
{
document.getElementById('div1').innerHTML = '<input id="btn3" type="button" onclick="changeText()" value="Change Text" />';
document.getElementById('btn1').setAttribute("aria-hidden",true);
}
and HTML:
<div id="div1">
<input id="btn1" type='button' onclick='changeText()' value='Change Text'/>
</div>
when I navigate to btn1 in windows with keyboard only(with tab) and then press enter(or space) the button is changed, but it lose focus. As you may see, I tried to focus it with JS, but without a result. I also tried to use tabindex tag, but didn't help too. I want it to be focused when it is pressed, so it will be easier to navigate and to be accessible for screen readers.
Please help!
EDIT
Focus has been tested on the button with James Long solution and it works!
However, the btn.setAttribute('aria-hidden', true); should be removed.
Final EDIT
I just got it, lol! In order to MY example to work properly, I have should be focus to btn2 instead of btn1. This is so silly! So, it goes as follows:
function changeText()
{
document.getElementById('div1').innerHTML = '<input id="btn2" type="button" onclick="changeText2()" value="Change Text2" />';
document.getElementById('btn2').focus();
}
function changeText2()
{
document.getElementById('div1').innerHTML = '<input id="btn1" type="button" onclick="changeText()" value="Change Text" />';
document.getElementById('btn1').focus();
}
I feel proud of my self :)
I don't have a screen reader to hand so it's tricky to test this, but you might have better luck changing a button rather than replacing it and focussing on the button itself.
<div id="div1">
<button type="button" id="btn1">Change Text</button>
</div>
And then your JS:
document.addEventListener('DOMContentLoaded', function () {
function changeText(btn) {
btn.textContent = btn.textContent === 'Change Text'
? 'Change Text2'
: 'Change Text';
btn.setAttribute('aria-hidden', true);
btn.focus();
}
document.getElementById('btn1').addEventListener('click', function (e) {
changeText(e.target);
}, false);
}, false);
Put the focus on your button :
$("#btn1").focus();
In pure JS :
document.getElementById('btn1').focus();

Switch to different button on click

I want code to switch the buttons. If I pressed button1 first time, it must show button2 and vice versa.
<input type="submit" value="asc" name="button1" id="but1">
<input type="submit" value="desc" name="button2" id="but3">
One solution without the need for JQuery would be this one:
<input type="button" value="asc" name="button1" id="but1" onClick="document.getElementById('but3').style.display='';this.style.display='none';">
<input type="button" value="desc" name="button2" id="but3" style="display:none;" onClick="document.getElementById('but1').style.display='';this.style.display='none';">
You can also do it this way if you want to use the visibility:
<input type="button" value="asc" name="button1" id="but1" onClick="document.getElementById('but3').style.visibility='visible';this.style.visibility='hidden';">
<input type="button" value="desc" name="button2" id="but3" style="visibility:hidden;" onClick="document.getElementById('but1').style.visibility='visible';this.style.visibility='hidden';">
Using visibility preserves the buttons position. I changed the type from submit to button just out of demonstration reasons.
You can look at both JSFIDDLE demos of these solutions here and here.
Not sure what you're trying to achieve, but you can use:
$('input[type="submit"]').click(function() {
$(this).hide().siblings('input[type="submit"]').show();
});
Fiddle Demo
Simply Use .toggle() in jQuery
$('input[type="submit"]').click(function() {
$('input[type="submit"]').toggle();
});
Fiddle
I'm betting your .toggle-radio-switch elements are siblings. Remove .parent() from your code. It isn't needed since .radio-switch-slider is contained directly in .toggle-radio-switch
$(this).find('.radio-switch-slider')
document.getElementById('but1').addEventListener('click', function() {
document.getElementById('but1').style.visibility = 'hidden';
document.getElementById('but3').style.visibility = 'visible'; }, false);
document.getElementById('but3').addEventListener('click', function() {
document.getElementById('but3').style.visibility = 'hidden';
document.getElementById('but1').style.visibility = 'visible'; }, false);
If you want to hide button and its placeholder completely, use style.display = 'none' and style.display = 'block'. If you put both buttons in div container with default static positioning, then both buttons will appear at the same position in container.
By default when page will load put following code so that your second button will be hide.
$(document).ready(function(e){
$('#but3').hide();
});
After that Put code that were
$('input[type="submit"]').click(function() {
$(this).hide().siblings('input[type="submit"]').show();
});
Try using the following functions:
$(element)click(callback) will handle the click of the element
$(element).show() will show the element
$(element).hide() will hide the element
so a semple code is:
//first hidden the second button
$('#but3').css('display','none')
// handle click of first button
$('#but1').click(function(){
$(this).hide()
$('#but3').show()
});
// handle click of second button
$('#but3').click(function(){
$(this).hide()
$('#but1').show()
});
Here is an example: http://jsfiddle.net/L7zux/1/
You can try the code below:
$('input[type="submit"]').click(function(){
var valueOfButton = $(this).val();
if(valueOfButton == 'asc')
{
$('input[value="asc"]').show();
$('input[value="desc"]').hide();
}
else
{
$('input[value="desc"]').show();
$('input[value="asc"]').hide();
}
});

Javascript - disable buttons on value matched in input box

i am looking for solution i want to disable button if value of input box matched.
i got two buttons and an input box
<button type="button" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value="0"/>
i want to disable buttonpassvalue if input box (count) is zero and disable second button buttonpassvalue1 if value of (count) is 5
thanks for your help.
Made a JSFiddle for you!
http://jsfiddle.net/fRHm9/
Basically, you make a change event listener and, when it changes, grab the element whose id is equal to the input's value. I assigned the buttons ids of -1 and 1. Check out the fiddle.
Basically, you could achieve this quite easily using plain javascript. But, when using javascript in order to be able to find a specific element efficiently you will need to specify an id for that element. So I would recommend you to change your buttons so that they use id attributes as follows...
<button type="button" id="buttonpassvalue" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button>
<button type="button" id="buttonpassvalue1" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>
<input type="text" id="count" value=""/>
Note, that I added id attributes to each buttons. Now, you can run attach this javascript function to the keyup event of the text input element...
var input = document.getElementById('count');
input.onkeyup = function(){
var buttonpassvalue = document.getElementById('buttonpassvalue');
var buttonpassvalue1 = document.getElementById('buttonpassvalue1');
var val = this.value.trim();
if(val == "0"){
buttonpassvalue.setAttribute("disabled","disabled");
buttonpassvalue1.removeAttribute("disabled");
}
else if(val == "5"){
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.setAttribute("disabled","disabled");
}
else{
buttonpassvalue.removeAttribute("disabled");
buttonpassvalue1.removeAttribute("disabled");
}
};
I have created a JS Fiddler where you can see a quick demo. Also, note that this solution is using plain javascript.

Disable button whenever a text field is empty dynamically

Here's my code:
<input type="text" onkeyup="if(this.value.length > 0) document.getElementById('start_button').disabled = false; else document.getElementById('start_button').disabled = true;"/>
<input type="button" value="Click to begin!" id="start_button" disabled/>
This works but still not efficient since the user can delete the text inside the text box and click the button while he's holding on DELETE key. Is there a more efficient way to achieve this using javascript?
Easiest way to do it :-
Simple Html and JavaScript : Run the snippet (Just 7 lines)
function success() {
if(document.getElementById("textsend").value==="") {
document.getElementById('button').disabled = true;
} else {
document.getElementById('button').disabled = false;
}
}
<textarea class="input" id="textsend" onkeyup="success()" name="demo" placeholder="Enter your Message..."></textarea>
<button type="submit" id="button" disabled>Send</button>
I have used textarea, but you can use any html input tags and try it out!
Happy coding!
Add a check when the button is clicked to see if there is any text. If there isn't, pop up an alert box (or some other form of feedback) to tell the user to enter data, and don't do the button functionality.
Example:
<input id="myText" type="text" onkeyup="stoppedTyping()">
<input type="button" value="Click to begin!" id="start_button" onclick="verify()" disabled/>
<script type="text/javascript">
function stoppedTyping(){
if(this.value.length > 0) {
document.getElementById('start_button').disabled = false;
} else {
document.getElementById('start_button').disabled = true;
}
}
function verify(){
if myText is empty{
alert "Put some text in there!"
return
}
else{
do button functionality
}
}
</script>
You could poll the value of the input. This would be less efficient and less responsive but potentially more reliable.
As you pointed out, the keyup event won't neccessarily fire when an input's value is cleared. What if they highlight the text with the mouse, right click and cut?
The change event might help, but it's still not all that reliable. It only fires on blur, and misses some changes (like an autocompletion selection).
Here's a jsFiddle demonstrating the polling solution.
In response to Eng.Fouad's comment, here's how to add the JS:
You could put it in a script tag, like this:
<script type="text/javascript">
//my code
</script>
That will work, but it will mean that your user's browser won't cache the JavaScript, meaning it will take longer to load your page. It's also cleaner to separate your scripts from your content. But if you want a quick and easy option, this should do. Put this at the bottom of your body and wrap it in a dom ready handler (see the bottom part of the answer).
As a cleaner option, you can put it in an external file e.g. someScript.js, the contents of which would be your JavaScript (with no script tags). You then link to that script from your HTML file:
<html>
<head></head>
<body>
<!-- contents of page -->
<script type="text/javascript" src="/path/to/someScript.js"></script>
</body>
</html>
NB: You need to make your script web accessible so that browsing to http://www.your-site.com/path/to/someScript.js accesses the script.
The script tag is at the bottom of the body so that the page loads the actual content first, and the scripts afterwards. This will mean that your content is visible to your users sooner.
You should make one last modification to the JavaScript in the jsFiddle. The jsFiddle has the code running "onDomReady" (see top left of the fiddle). Technically, you don't need to do this if you have your script after your content. It's there to ensure that the script runs after the content has loaded, so that if the script attempts to find elements in the DOM, they have been loaded, and are found. You should probably add this to the script in case (for some reason) you move the script to before the content. In order to wrap your script in a dom ready handler in jQuery, do this:
$(function(){
// my code
});
In that example, code put where the //my code comment is will be run only when the page is ready.
<input type="number" id="abc" onkeyup="s()">
<input type="submit" id="abc2" disabled >
<script type="text/javascript">
function s(){
var i=document.getElementById("abc");
if(i.value=="")
{
document.getElementById("abc2").disabled=true;
}
else
document.getElementById("abc2").disabled=false;}</script>
This is what worked for me. I hope it works for someone else. I needed the button disabled when the user didn't have any text or when they deleted the text.
$('#textarea').on('keypress keyup keydown', function () {
if ($('#textarea').val() == "" ) {
$('#savebtn').prop('disabled', true);
}
else {
$('#savebtn').prop('disabled', false);
}
});
$('#textarea').on('keypress keyup keydown', function () {
if ($('#textarea').val() == "" ) {
$('#savebtn').prop('disabled', true);
}
else {
$('#savebtn').prop('disabled', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" onkeyup="if(this.value.length > 0) document.getElementById('start_button').disabled = false; else document.getElementById('start_button').disabled = true;"/>
<input type="button" value="Click to begin!" id="start_button" disabled/>
Here button is disabled by default and when keyup event is triggered, check if text field value is length is zero or not. If zero then button is disabled, else enabled.
<head>
<title>Testing...</title>
</head>
<body>
<input id="myText" type="text" onkeyup="btnActivation()">
<input type="button" value="Click to begin!" id="start_button" disabled/>
<script type="text/javascript">
function btnActivation(){
if(!document.getElementById('myText').value.length){
document.getElementById("start_button").disabled = true;
}else{
document.getElementById("start_button").disabled = false;
}
}
</script>
</body>

Categories