Why JavaScript IF only works once? - javascript

I have JavaScript code which copies the value of input file and paste it in the text box in real time.
<script>
function copyit(){
var thephoto=document.getElementById('thephoto').value;
var fileonchange=document.getElementById('fileonchange').value;
if(!thephoto==fileonchange){
document.getElementById('fileonchange').value=thephoto;
}
}
window.setInterval("copyit()", 500);
</script>
Choose File : <input type="file" id="thephoto"><br>
Here Is the file name : <input type="text" id="fileonchange">
Sadly this only works once and then stops pasting the value when changing the file again. (I mean you should reload the page to make it work again)
Does IF have a cache or something? You can try the code by yourself to see.

The syntax is wrong. You need the != operator to denote inequality:
if (thephoto != fileonchange) {
The !thephoto actually inverses its boolean representation (i.e. true becomes false and vice versa, also null becomes true). The == actually compares the equality of the both operands.

Try changing the IF line to:
if(thephoto!=fileonchange){

BalusC is completely right, but IMHO using a timer every 500ms to do this simple task seems pretty heavy.
Why don't you simply use the onchange event of the <input type="file" />?, e.g.:
window.onload = function () {
var thephoto = document.getElementById('thephoto');
var fileonchange = document.getElementById('fileonchange');
thephoto.onchange = function () {
// this function will be executed when the user changes the file
fileonchange.value = this.value;
};
};
Check the above example here.

The input element, as the W3C says, accepts the onchange method. Why don't you do:
<input type="file" id="thephoto" onchange="copyit()">
Instead of using the dreaded setInterval?

Use !== for strict inequality.
Or, if you want to use something similar to the syntax you've written, do this:
if(!(thephoto==fileonchange)){

Related

Not repeating selectors in a conditional statement with JavaScript/jQuery

I have a small app with one form and one input field. When a user submits this form, I first want to see if the value only contains letters. If all is good, I want to pass the value on to a function.
Here's what I have:
$('form').on('submit', function(e) {
if ($('input').val().match(/^[a-zA-Z]+$/)) {
someFunction($('input').val());
} else {
// Error message or something else here
}
e.preventDefault();
});
I don't like writing $('input').val() twice (once in the conditional statement, and again if it holds true). Using this wouldn't work, since it's within a conditional statement and not some sort of function... Is there a way to not repeat code in this scenario?
Perhaps setting $('input').val() to a variable would be best?
Thanks!
Just do this:
var inputValue = $('input').val();
Bit old but I found this helpful : Not repeating selectors
var myvar = $('input');
As well as the clear discription :
basically every time you use $(someselector) you iterate through the dom. If you can you should store the element reference

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

How do you programmatically clear HTML5 date fields?

I'm looking for a way to programmatically clear HTML5 date fields with Javascript (specifically jQuery). So far I have tried two methods which I thought obvious:
$('input[type=date]').val('');
$('input[type=date]').val('0000-00-00');
But neither of them work on the latest version of Chrome for PCs at least, haven't tried them with other browsers or platforms yet. Is there an API call or something that can clear date fields in a cross-browser way? Solutions I have searched for like this require the user to clear the date field whereas I need this to be done programmatically.
$("input[type=date]").val("") works for me in chrome. It sets the input field to dd/mm/yyyy.
Maybe it's browser specific. Most browsers have only partial or no support for this input: http://caniuse.com/input-datetime
If you can't clear a date field, this could also depend on a browser bug.
I spend some time until I found out that you cannot reset the date in Firefox if the date control is disabled.
See: https://bugzilla.mozilla.org/show_bug.cgi?id=1465979
Without the bug, I am able to clear the date like that:
document.getElementById("myDate").value = "";
I needed to do it recently and i've made this little hack... Seems to do the job.
It was just with JavaScript, but the jQuery version is pretty the same...
function reset_date_native() {
var date_input = document.getElementById('date-id');
//erase the input value
date_input.value = '';
//prevent error on older browsers (aka IE8)
if (date_input.type === 'date') {
//update the input content (visually)
date_input.type = 'text';
date_input.type = 'date';
}
}
function reset_date_jquery() {
$('#date-id').val('')
.attr('type', 'text')
.attr('type', 'date');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="date-id" type="date" />
<button onclick="reset_date_native()">Trigger the reset function (native)</button>
<button onclick="reset_date_jquery()">Trigger the reset function (jQuery)</button>
document.getElementById("datePicker").valueAsDate = null;
this line of code works with my browser (chrome) , didn't tested in other browsers
You can change the date as empty
$('#invoiceDate').val(new Date())
You can restore the placeholder;
$('input[type=date]')[0].valueAsDate = '';
this line works with my browser (chrome, latest version)
$('input[type=date]')[0].value = 0;
Can you use the reset function of your form ?
You can do this with reset button :
<button type="reset" value="Reset">Reset</button>
or programmaticaly :
$("#yourFormId").reset();
or
$('input[type=date]').reset();
Use the native defaultValue property:
$('input[type=date]').each( function resetDate(){
this.value = this.defaultValue;
} );
This works as long as the form doesn't have an initial value specified, as demonstrated in this fiddle.
This solution checks if a default value exists and, if so, uses it to reset the input. Otherwise, it clears the input it by updating value and valueAsDate.
Info on valueAsDate available at: w3c.org.
var dateEl = element.find('input#myDateInput[type="date"]');
dateEl[0].value = ('undefined' !== typeof dateEl[0].defaultValue) ? dateEl[0].defaultValue : '';
if (dateEl[0].value !== '') {
dateEl[0].valueAsDate = new Date(dateEl[0].value);
} else {
dateEl[0].valueAsDate = null;
}
I had a similar issue with the value.
I wanted the onchange() function to run when I set the value to empty. Normally, this always works but for date it didn't even if the value appeared to be blanked and you blurred the input
I discovered that I had to force the onchange() function to trigger the value change too.
document.getElementById('mydate').value='';
document.getElementById('mydate').onchange();
It worked for me and now my form fades out when the value is blanked.
I do not know why that works. I tried blur() and focus() but nothing else seems to work.
Set myDate = one space.
I like simple solutions.

jquery masked input plugin to not clear field when errored

I'm looking at the http://digitalbush.com/projects/masked-input-plugin/
I'm calling it like this:
$(control).mask('999-999-9999');
And I don't want it to throw away the users input if something is wrong, e.g. they haven't finished
[407-555-____]
If you leave the field after having typed this much, it clears it. I'd like to leave it so they can finish later.
I'm new to jQuery, and I've looked through his source, but I can't find any way to do that, nor can I find any way to edit it to accomplish what I want, because the code is arcane to my eyes.
Set autoclear option to false.
$(control).mask('999-999-9999', {autoclear: false});
It looks like I should just make the whole mask optional:
mask('?999-999-9999')
That way the control thinks what the user has is "valid" and I can continue. Even though it isn't really the optional part of the mask.
You should delete statement input.val(""); in checkVal() function for a proper solution.
If you're using minified version, you should search and delete statement:
if(!a&&c+1<i)f.val(""),t(0,k);else
Try update file jquery.maskedinput.js
In function function checkVal(allow) set parameter allow on true. Its help for me.
function checkVal(allow) {
allow = true; ///add this command
//..............
}
In addition to removing the input.val("") in checkVal() you can also change the call to clearBuffer.
In the original code it is: clearBuffer(0, len); removing all user input.
if you change this to clearBuffer(lastMatch + 1, len); the user input will be displayed, followed by the mask placeholders that are still needed to complete correct input.
I have also added a user message in the .bind. This works for us, as we are using the MaskedInput for exactly one type of input. I'm checking for any input going further than position 7, because that's where the user input starts.
Here is what I did:
.bind("blur.mask", function() {
// find out at which position the checkVal took place
var pos = checkVal();
// if there was no input, ignore
if (pos <=7) {input.val(""); clearBuffer(0, len);}
// if the user started to input something, which is not complete, issue an alert
if (pos > 7 && pos < partialPosition) alert("Tell the user what he needs to do.");
if (input.val() != focusText)
input.change();
})
Adding Placeholder could solve the problem.
$(control).mask('999-999-9999');
Add an empty place holder into mask. see below
$(control).mask('999-999-9999', { placeholder: "" });
which would replace _ on the input text field by default. so there would bot be any _ left if the input length is dynamic and not fixed.
Looking for into the pluging script the unmask method.
$('#checkbox').unmask();

How can I ensure that changes to a form DOM are complete before POSTing?

Currently I have a race condition existing in my JavaScript code. What I am trying to do with this code is convert all check boxes which are a part of the 'checkbox' class and are not checked into text boxes with a value of zero. Currently when you post a check box that is not checked it does not appear in the $_POST data. However I need to know all the values whether true or false for these particular set of check boxes.
The code I have is here:
Code:
function checkboxConvert() {
var chkBxs = $$('.checkbox');
for (var i = 0; i < chkBxs.length; i++) {
if (chkBxs[i].checked == false) {
chkBxs[i].type = 'textbox';
chkBxs[i].value = '0';
}
}
setTimeout("document.productForm.submit();",1000);
}
Now the problem that I have been getting is that when I try to submit this form the values of the recently changed text boxes does not appear in the $_POST data. Therefore, as you can see above I have postponed the page submit for 1 sec and then I have all the data available to me. However as time goes on and my data set gets larger, 1 sec may no longer be enough. This I think is a race condition and I need to figure some way of running the code only after all the check boxes have been converted and they have their new values. I would have thought that this would be unnecessary from the start, but for some reason it's trying to run both pieces simultaneously and I can't submit until I have the proper values in place.
Any help is much appreciated!
This is definitely not the way to do web. I strongly advise you abandon your checkboxConvert function, and solve this issue on the server side
JavaScript always runs single-threaded in the browser so I don't think it can be a race condition.
I'd generally agree with others that you shouldn't do this, but your problem may be that you're changing the element to a type of "textbox" instead of "text". If you declare an input of type "textbox" in HTML markup, it will usually render as a text field anyway because that's the default. However, changing an already valid "checkbox" type input to the invalid "textbox" may not work predictably.
Try changing it to this:
function checkboxConvert() {
var chkBxs = $$('.checkbox');
for (var i = 0; i < chkBxs.length; i++) {
if (chkBxs[i].checked == false) {
chkBxs[i].type = 'text';
chkBxs[i].value = '0';
}
}
// Because JS in the browser is single-threaded, this
// cannot execute before the preceding loop completes anyway.
document.productForm.submit();
}
There's got to be a better way to do this. Try something like:
Know about all your possible values on the server side. It looks like you're using PHP; keep a simple array with the names of your checkboxes.
When you take your $_POST data, remove the names of checkboxes you've received values for from your array.
The remaining are all false.

Categories

Resources