I am using the jQuery Mobile and Phonegap to create a Study Timer and I am trying to change a form value through JS.
The form value:
<form action="javascript:void(null);" id="theTimer" name="theTimer">
<input id="timerDisplay" type='text' name="theTime" readonly/>
<br />
<input type='submit' name="start" value="Start" onclick="Start()"/>
<input type='submit' name="stop" value="Stop" onclick="Stop()"/>
<input type='submit' name="pause" value="Pause" onclick="Pause()"/>
</form>
The JS code:
function Pause() {
if (timerID) {
clearTimeout(timerID);
}
if (myTimer) {
clearInterval(myTimer);
}
if (document.theTimer.pause.value == "Pause") {
document.theTimer.pause.value = "Resume";
} else {
document.theTimer.pause.value = "Pause";
tToday = new Date();
total_time = tToday.getTime() - tDiff;
tStart = new Date(total_time);
timerID = setTimeout(UpdateTimer, 1000);
startTimer();
}
}
The problem is that when I was using another framework the form value Pause would change to Resume and Resume to pause through the Pause() function... now it doesn't see the Pause form value at all...
What am I missing to get to form value Pause to change to Resume?
If you are using jquery, you could be doing:
if ($('input[name=pause]').val() == "Pause") {
$('input[name=pause]').val("Resume");
}
instead of
if (document.theTimer.pause.value == "Pause") {
document.theTimer.pause.value = "Resume";
}
The scope of the variables within your function is confusing because you've omitted the var keyword on all of them. I would first clean up your variable declarations, and use the power of jQuery instead of manually fighting your way through the DOM to set values:
<form action="javascript:void(null);" id="theTimer" name="theTimer">
<input id="timerDisplay" type="text" name="theTime" readonly="readonly" />
<br />
<input type="submit" name="start" id="start" value="Start"/>
<input type="submit" name="stop" id="stop" value="Stop"/>
<input type="submit" name="pause" id="pause" value="Pause"/>
</form>
I removed your onclick events and fixed your readonly attribute, and your quotes. I think part of the problem is that you were submitting the form when clicking the buttons and the page was posting back. Your timers were resetting when this happened causing unexpected behavior. I'm adding back the functions using jQuery:
$(function() {
$('#start').click(function() {
Start();
return false;
});
$('#stop').click(function() {
Stop();
return false;
});
$('#pause').click(function() {
Pause();
return false;
});
});
var timerID, myTimer;
function Pause() {
if (timerID) {
clearTimeout(timerID);
}
if (myTimer) {
clearInterval(myTimer);
}
if ($('#pause').val() == "Pause") {
$('#pause').val("Resume");
} else {
$('#pause').val("Pause");
var tToday = new Date();
var total_time = tToday.getTime() - tDiff;
var tStart = new Date(total_time);
timerID = setTimeout(UpdateTimer, 1000);
startTimer();
}
}
Perhaps you could fill in the gaps in your question with what startTimer() and UpdateTimer() do? Also, you haven't really explained what your issue is exactly... could you indulge us?
Don't use submit buttons, use <input type="button" ...>. Your form is posting and returning a new page with the buttons in their default settings.
You can forget the xml-style markup, it's just wasted characters. And void is an operator, not a function, so you don't need to follow it with the grouping operator (). You don't need it anyway, the required action attribute can be anything, '#' is sufficient in this case - if the form isn't submitted, it won't go anywhere.
<form action="#" id="theTimer" name="theTimer">
<input id="timerDisplay" type="text" name="theTime" readonly>
<br>
<input type="button" name="start" value="Start" onclick="Start()">
<input type="button" name="stop" value="Stop" onclick="Stop()">
<input type="button" name="pause" value="Pause" onclick="Pause()">
</form>
By convention, identifiers starting with a capital letter are reserved for constructors and identifiers with all captial letters for constants.
Related
I have been trying to find a solution for days now. I am not strong in javascript and it confuses me.
I want the submit button disabled unless the start time is earlier that the end time. I can do this so easily in PHP but I need to prevent submission of a form on the client side in this case. I was able to figure out basic numbers but not date-times. I also would like to insert a message inside of the div tags with the id of message.
<input type="datetime-local" name="start" id="start">
<input type="datetime-local" name="end" id="end">
<div id="message"></div>
<button type="submit" name="submit" id="submit">Click to Submit</button>
This should do the trick:
<input type="datetime-local" name="start" id="start">
<input type="datetime-local" name="end" id="end">
<div id="message"></div>
<button type="submit" name="submit" id="submit">Click to Submit</button>
<script type="text/javascript">
let startInput = document.getElementById('start');
let endInput = document.getElementById('end');
let messageDiv = document.getElementById('message');
let submitButton = document.getElementById('submit');
let compare = () => {
let startValue = (new Date(startInput.value)).getTime();
let endValue = (new Date(endInput.value)).getTime();
if (endValue < startValue) {
messageDiv.innerHTML = 'Start date must be before end date!';
submitButton.disabled = true;
} else {
messageDiv.innerHTML = '';
submitButton.disabled = false;
}
};
startInput.addEventListener('change', compare);
endInput.addEventListener('change', compare);
</script>
First, we store all the HTML elements we need in variables. Then we declare a function that we run whenever either date input changes. Inside that function, we check if the end date is before the start date. If it is, we display the error message and disable the submit button; if it isn't, we hide the error message and enable the submit button.
I ran this code and it works.
Comment on this answer if you have questions.
something like that ?
<form id="my-form">
<input type="datetime-local" name="start" >
<input type="datetime-local" name="end" >
<div id="message"></div>
<button type="submit" name="btSubmit" disabled>Click to Submit</button>
</form>
const myForm = document.getElementById('my-form')
myForm.end.oninput=()=>
{
let d_start = (new Date(myForm.start.value)) || Infinity
, d_end = (new Date(myForm.end.value)) || 0
myForm.btSubmit.disabled =( d_start > d_end)
}
I know this question has been asked already.
However, when I follow the answer given to that question it doesn't work.
This is my JS function and the relevant HTML
function myFunction() {
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button onclick="myFunction(document.getElementById("number").value)" class="Button" >Submit</button>
<p id="submit"></p>
<script type ="text/javascript" src="../src/index.js"></script>
Strangely none of the answers recommended separating the HTML and JavaScript, so that's what I'll do. It's considered a best practice to not inline JS in your HTML.
const button = document.querySelector('button');
button.addEventListener('click', myFunction, false);
function myFunction() {
console.log(document.getElementById('number').value);
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button class="Button">Submit</button>
<p id="submit"></p>
Try this...
Get the value insert the function.... It will display your desire output....
function myFunction() {
var number = document.getElementById("number").value;
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button onclick="myFunction()" class="Button" >Submit</button>
<p id="submit"></p>
<script type ="text/javascript" src="../src/index.js"></script>
Like the earlier answer, you need to use single quote around 'number'. Another thing, you need to add parameter val in the myFunction(val) in the index.js.
function myFunction(val) {
document.getElementById("submit").innerHTML = "LOADING...";
console.log(val);
}
I thought, You used inside double quote("), using double quote("). So Please change double quote inside single quote(') or single quote inside double quote("). More over button default type is submit...
Change following
<button onclick="myFunction(document.getElementById("number").value)" class="Button" >Submit</button>
Into
<button onclick="myFunction(document.getElementById('number').value)" class="Button" >Submit</button>
or
<button onclick='myFunction(document.getElementById("number").value)' class="Button" >Submit</button>
javascript
function myFunction() {
document.getElementById("submit").innerHTML = "LOADING...";
}
Into
function myFunction(num) {
var n = num;//Get the number into your javascript function
document.getElementById("submit").innerHTML = "LOADING...";
}
<input class="textbox" type="number" id="number">
<button onclick="myFunction(document.getElementById('number').value)" class="Button" type="button" >Submit</button>
<p id="submit"></p>
<script type="text/javascript">
function myFunction(num){
var n = num;
console.log(n);
document.getElementById("submit").innerHTML = "LOADING...";
}
</script>
Default type of the button element is submit (and it is ok; the data will be submitted to the server). If something should be done before submission then it could be processed like this.
function myFunction(element, evn) { //here you can rename parameters
//evn is click event, element is the button clicked
evn.preventDefault(); //don't submit form at this moment
document.getElementById("submit").innerHTML = "LOADING...";
//now it is safe to submit the form
//setTimeout is for demonstration purpose
setTimeout(function() {
element.form.submit();
}, 1000);
}
<!-- form tag supposed to be open -->
<form method="get" action=".">
<input class="textbox" type="number" id="number" name="numData">
<!--name attr is required to send data to the server -->
<!-- note the arguments sent to the function.
Don't change them -->
<button onclick="myFunction(this,event)" class="Button">Submit</button>
<!-- form tag may be closed here or later -->
</form>
<p id="submit"></p>
<script type="text/javascript" src="../src/index.js"></script>
what I am missing in this code, If I just want the input submit button to enable/disable/enable.. as long as I fill or unfill the input text?
sorry I am doing my best to learn javascript...can anyone help me fix this code?
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value=""/>
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
<script>
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
</script>
This is the fiddle: https://jsfiddle.net/1zfm6uck/
Am I missing declaring onLoad mode or something like this?
Thanks!
Actually - if it wasn't a jsfiddle example your code would work great:
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
input[type='submit']:disabled{
color:red;
}
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value="" required="required" />
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
The problem was the jsfiddle put your javascript code inside a clousure, so the checkFormsValidity function is not available in the scope of your input.
I added a required="required" to your input to make sure it's a required field (which will affect the checkValidity() of your form).
function checkFormsValidity(){
needs to be change to:
checkFormsValidity = function(){
Personally I wouldn't check validity that way, but in terms of making your code work without error, that will do it.
Edit: Also add required="required" to the input.
I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle
Here is my code :
<form>
<input type="text" id="input"/>
<br/>
<div id="buttons">
<input id="search" onclick="search()" type="button" value="Search"/>
<input type="button" value="Random"/>
<script type="text/javascript">
function search() {
var search = document.getElementById('search');
var int = setInterval(function() {
if (search.value.length == 6) search.value = 'Searchi';
else if (search.value.length == 7)
search.value = 'Searchin';
else if (search.value.length == 8)
search.value = 'Searching';
else {
search.value = 'Search';
}
//clearInterval( int ); // at some point, clear the setInterval
}, 500);
}
</script>
</div>
</form>
the button function is not working when <form> element is in the code. by removing the form element you will see that the JavaScript works! I want to know what is the problem? and how can I fix it?
Also, is there a better code for the result that I want? Somebody told me that I am using an old method of JavaScript!
Change the element id-search which hides in IE the function search of the global object:
<input id="search" onclick="search()" type="button" value="Search"/>
Should be:
<input id="search-suffix" onclick="search()" type="button" value="Search"/>
P.S.
int is a reserved word in javascript though it doesn't do anything in the meanwhile, just like class and private etc', thus should be avoided.