onblur to onsubmit not working as expected - javascript

I have this code which works as expected (executes when the user clicks out of the entry field)
<input id="sampleID" name="sampleID" type="text" onblur="myfunction(sampleID.value); "/>
However I'm having trouble figuring out how to have this work when the user hits the 'enter' button. Ive tried:
<input id="sampleID" name="sampleID" type="text" onkeyup="if (event.keyCode==13) myfunction(sampleID.value); "/>
but this clears the form input field

key13 is the return/enter key. You probably wanted onblurs sister event change. In order to stop the page from clearing the page, use preventDefault(). That will stop the ENTER/RETURN key from triggering a submit event on the <form>. The following Snippet demonstrates both.
SNIPPET
function test(val) {
console.log('You have entered: ' + val);
}
<form id="f1">
<label for="testKeyup">Type in box and press the <kbd>ENTER/RETURN</kbd> key</label>
<input id="testKeyup" name="testKeyup" type="text" onkeyup="if (event.keyCode==13) test(this.value); event.preventDefault()" />
<br/>
<br/>
<label for="testChange">Type in box and then click anywhere <b>but</b> this box</label>
<input id="testChange" name="testChange" type="text" onchange="test(this.value);event.preventDefault();" />
</form>

Related

Retain value in a disabled input when reset button is pressed

I am using a project code input in my form as
<input type="text" id="txtProjectCode" name="Project Code" class="form-control" maxlength="15" disabled="disabled" />
When I reset my form using my reset function
function resetRequestForm() {
$("#txtProjectCode").val(userProject);
}
I am trying to add value again through global variable, but still it is not reflecting in the form.
Please help on this
Please see this example. It is not exactly what you are doing.
But I am only showing the way how to do it.
Here It is working with disabled also, but please note that disabled fields value will not post on the server end.
var userProject = 'My Project';
function resetRequestForm() {
$("#txtProjectCode").val(userProject);
}
function getValueAgain(){
console.log($("#txtProjectCode").val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtProjectCode" name="Project Code" class="form-control" maxlength="15" readonly />
<button onClick="resetRequestForm()"; >resetRequestForm</button>
<button onClick="getValueAgain()"; >getValueAgain</button>
Disabled input text
<input type="text" id="txtProjectCode" name="Project Code" class="form-control" maxlength="15" disabled="disabled" />
Clear Button
<button class="clear_button" onclick ="return resetForm();" id="clearRequest">Clear</button>
This will retain the data in the disabled input, when
the form is cleared using a button with custom resetForm() function
the button type is set as `reset'
Note:
Data will not be retained if readonly="readonly" is used instead of disabled="disabled" (in both the cases)
no need to feed the data again as $("#txtProjectCode").val(userProject); - userProject is a global variable.

How to make pop up show up after the fields of the form are fulfilled?

I'm making a website for a project and I've added a subscribe to our newsletter section and I've set up a pop when you click the subscribe button. Before I added that js, the form wouldn't proceed until both fields were filled out and it showed a popup telling you to fill it.
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily
Newsletter
</label>
<input type="submit" value="Subscribe" onclick="myFunction1()">
Now with the js, it shows the pop up I made thanking the person for subscribing when I click the subscribe button regardless if the fields are filled or not.
function myFunction1() {
alert("Thanks for subscribing!")
}
You should include all the inputs in a form tag, as so:
<form id='myForm'>
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily
Newsletter
</label>
<input type="submit" value="Subscribe" onclick="myFunction1()">
</form>
This approach is better because then all the inputs are together in one entity, without it the 'submit' input won't really work. It won't know what is being submitted. Within the form tag it knows it's submitting the form together with all inputs contained within.
The form tag has its own set of events that you can add listeners to.
Including a 'submit' event.
To add the event listener to run your function whenever a submit happens on the form, you can do as so:
document.getElementById('myForm').addEventListener('submit', myFunction1)
Alternatively, you can also set the listener on the html:
<form onsubmit='myFunction1()'>
But keep in mind that with the 'addEventListener' method you can add multiple listeners to the same event. While the onsubmit property only accepts one function.
More info on events and on the addEventListener method:
https://developer.mozilla.org/en-US/docs/Web/Events
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
inside the function check for the field values. Confirm whether the fields are empty. If not then show the alert
function myFunction1() {
var f1 = ; // get value of field1;
var f2 = ; // get value of field2;
if (f1 != '' && f2 != ''){
alert("Thanks for subscribing!");
}
}
give all inputs of class, eg: 'myInput', and loop over them to check their value before alerting.
function myFunction1() {
var inputs = Array.fom(document.getElementsByClassName('myInput'));
var allChecked = false;
inputs.map(function(input){
if (input.value == '') { allChecked = false }
});
if (allChecked) { alert("Thanks for subscribing!") }
};

Javascript Issue - HTML division Calculator

I'm in the learning phase the code works fine no issues, however I need to add the below features.
When clicking the mouse on the calculate button it does the calculation and spits the results out correct, however my question is I'd want to use the physical keyboard "enter key" to execute/press the calculate button.
Also I need the form to reset after 5 seconds automatically, how can I do that ?
.
<script Language="Javascript">function Calc(myform){var enternumber1=document.myform.number1.value;var enternumber1=parseFloat(enternumber1,10);if(isNaN(enternumber1)||(enternumber1<0)){alert(" Enter a valid number! ");document.myform.number1.value="";document.myform.number1.focus();}else{var enternumber2=document.myform.number2.value;var enternumber2=parseFloat(enternumber2,10);if(isNaN(enternumber2)||(enternumber2<0)){alert(" Enter a valid number! ");document.myform.number2.value="";document.myform.number2.focus();}else
document.myform.number3.value=enternumber1/enternumber2;}}</script>
<form name="myform">
<br />
<b>Enter your first number:</b> <input maxlength="" name="number1" size=" " type="text" /><br />
<br />
<b>Enter your second number:</b> <input maxlength="" name="number2" size="" type="text" /><br />
<br />
<input name="button" onclick="Calc(myform)" type="button" value="Calculate" /> <input name="Reset" type="Reset" /><br />
<br />
<b>The result is :</b> <input maxlength="" name="number3" size="" type="text" value="" /> </form>
Please try to be clear in whatever you are asking. Lets move to your query now:
From your query I can understand that you are facing issues in doing 2 things:
Calling your Calc('myform') function when Enter key is pressed in second input field. - I am not covering validation of form(should have validation function,to be called before calling Calc() function). Just add an id to both the form tag as well as the second input field.Let say you add myForm and num2 ids in form and second input field respectively.
Once added you can use following function:
<script type="text/javascript">
document.getElementById('num2').onkeypress = function (event) {
if (event.keyCode == 13) {
Calc(myform);
}
};
</script>
**Note:**In this function we are checking every key which is getting pressed when our cursor is in num2 field, if the key pressed is having code 13,which is the keycode of enter key, I am just calling the same function Calc() which you are already using.So it will do the same what its doing on click of Calculate button.
For resetting your form in every 5 seconds.Please add this function:
function resetForm() {
document.getElementById("myForm").reset()
}
setInterval(resetForm, 5000);
Note: We are calling setInterval function here to reset your form in every 5seconds.Please dont forget to add myForm id in your form.

How do set to open an specific link on submit button based on the 2 separate radio buttons

Here is the Code I written
<form>
<input type="radio" name="cand" value="fr" onclick="alert('You Have Selected Fresher Level \nPlease Click Next To Proceed');"> Fresher<br><br>
<input type="radio" name="cand" value="ex" onclick="alert('You Have Selected Experienced Level \nPlease Click Next To Proceed');"> Experienced<br><br>
<input type="button" onclick="location.href='http://google.com';" value="Next" />
</form>
If suppose user select option 1 (say: freshers) then Link 1 (Fresher form link) Should be open.
or If select option 2 i.e experienced then experienced link should open.
Please Provide Answer with explanation, I am new to HTML and JavaScript.
You need script to update the location.href' . Trigger a function on selecting radio button and update theonclickproperty usingsetAttribute` method
function updateLink(value) {
if (value === "fr") {
document.getElementById("next").setAttribute('onclick', "location.href='www.google.com'")
} else {
document.getElementById("next").setAttribute('onclick', "location.href='www:wikipedia.com'")
}
}
<form>
<input type="radio" name="cand" value="fr" onclick="updateLink(this.value)"> Fresher<br><br>
<input type="radio" name="cand" value="ex" onclick="updateLink(this.value)"> Experienced<br><br>
<input id="next" type="button" onclick="location.href='www.google.com';" value="Next" />
</form>
This demo is just based on your code. Using addEventListener is a better option than using inline event handler.
Do like this.
Try to submit the form and prevent the default behaviour of the form using e.preventDefault()
Then change the input button type with submit
And add the data-link attr for Each input .For applying with window targeted link after submit
How its work
if you submit the form .its find the checked radio button data-link then
apply with window.location.Finaly its redirect the respected url
$('from').on('submit',function(e){
e.preventDefault();
window.location.href = $('input:checked').attr('data-link');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
<input type="radio" name="cand" value="fr" data-link="Fresher"onclick="alert('You Have Selected Fresher Level \nPlease Click Next To Proceed');" > Fresher<br><br>
<input type="radio" name="cand" data-link="Experienced" value="ex" onclick="alert('You Have Selected Experienced Level \nPlease Click Next To Proceed');" > Experienced<br><br>
<input type="submit"/>
</form>
In the example below I add an attribute to each radio. When the user clicks on the button we fetch that attribute (data-href) and use window.location.href to transfer the user there. You can use value instead, if you find that better. Note that I removed the inline click-function and use an event for it instad.
$('#clickButton').click(function(){
var url = $('input[name=cand]:checked').data('href');
//Goto url
window.location.href = url;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" name="cand" value="fr" data-href="https://www.stackoverflow.com" onclick="alert('You Have Selected Fresher Level \nPlease Click Next To Proceed');" > Fresher<br><br>
<input type="radio" name="cand" value="ex" data-href="https://stackoverflow.com/q/45627889/4949005" onclick="alert('You Have Selected Experienced Level \nPlease Click Next To Proceed');" > Experienced<br><br>
<input type="button" id="clickButton" value="Next" />
</form>

JS - Focus/Select Cursor Again after Toggling Div

I have a landing page with two forms, only one form visible at a tme. The first form is an age-verification form and if the conditions are met I use jQuery .toggle() to switch to the next form. On page load, for good UX I am using .focus() to put the cursor in the first form field with this line of code: $("input[name='month']").focus();
// Focus cursor on first input field
$("input[name='month']").focus();
var age = 19;
// After calculating age based on user input, toggle the elements
if (age >= 18) {
$('#age-verification').toggle();
$('#subscribe').toggle();
} else {
$('#age-verification').html('<h2>Sorry, you must be at least 18 years old.</h2>');
}
<div id="age-verification">
<h2>Must be 18, please verify age</h2>
<input type="number" name="month" />
<input type="number" name="day" />
<input type="number" name="year" />
<button id="age-gate-submit">Submit</button>
</div>
<form id="subscribe" action="#" method="post">
<input type="text" name="email" />
<input type="text" name="zip" />
<button id ="subscribe" type="submit">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
How can I use either .select(), focus() or other method to place the cursor in the first field of the second form <input type="text" name="email" /> after the .toggle() event? I've tried placing a .focus() event direct after the .toggle() which seemed logical but not successful.
You need to first hide the subscribe form:
$('#subscribe').hide();
Working demo: http://jsbin.com/kihepujewi/edit?html,js,output

Categories

Resources