onmouseover doesn't function when onchange does? - javascript

I've got a little script that toggles a button between disabled and not depending on the value of a number input. It works exactly as I'd expect when the event trigger is input.onchange, but it doesn't seem to work if I try to make the event button.onmouseover.
This works:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input onchange="myFunction()" type="number" id="quantity" name="quantity" min="1" max="5">
<input disabled id="submit" type="submit">
<p id="number"></p>
</form>
<script>
function myFunction() {
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value >= "5") {
y.toggleAttribute("disabled");
} else if (y.hasAttribute("disabled") == false) {
y.toggleAttribute("disabled");
}
}
</script>
This does not:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<input onmouseover="myFunction()" disabled id="submit" type="submit">
<p id="number"></p>
</form>
<script>
function myFunction() {
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value >= "5") {
y.toggleAttribute("disabled");
} else if (y.hasAttribute("disabled") == false) {
y.toggleAttribute("disabled");
}
}
</script>
If I remove the inital disabled attribute from the button, my else if toggle works, but the first if never toggles it off. Is there something about onmouseover that prevents it from checking the quantity value?

In HTML, disabled elements don't fire events, you can't hover or click them.
You can wrap such element within a div and fire mouseover on that div.
Here's code:
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<div style="display: inline;padding: 10px;" id="wrapper_submit">
<input disabled id="submit" type="submit">
</div>
<p id="number"></p>
</form>
<script>
// After page load
window.onload = function(){
// Get div and on its mouseover
document.getElementById("wrapper_submit").onmouseover = function(){
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value > "5") y.disabled = true;
else if(x.value >= "1") y.disabled = false;
}
}
</script>
Edit: Mouseover event only fires when cursor is over element it self, it will not fire if child element covers parent. In above case if you remove padding from [Div('wrapper_submit')], mouseover event will not work.
Use mouse enter event, it works even if child covers parent 100%.
document.getElementById("wrapper_submit").onmouseenter = function(){
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value > "5") y.disabled = true;
else if(x.value >= "1") y.disabled = false;
}

It happens because your input is disabled and it doesn't react
Try this code and let me know if it works to you
<form action="/action_page.php">
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<input onmouseover="myFunction()" disabled id="submit" type="submit">
<p id="number"></p>
document.getElementById("quantity").onmouseover = function() {myFunction()};
function myFunction() {
var x = document.getElementById("quantity");
var y = document.getElementById("submit");
if (x.value < "5" ) { y.removeAttribute("disabled"); }else if (x.value>= "5") {
y.toggleAttribute("disabled");
} else if (y.hasAttribute("disabled") == false) {
y.toggleAttribute("disabled");
}
}

Related

Disable button if a sum of number inputs is of certain value (JS)

Given this HTML code:
<body onload="assessSum()">
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>
</body>
What would be a function that would disable the submit button, if the sum of the 2 input fields is greater than a certain value?
My JavaScript/Jquery code doesn't seem to work:
function assessSum(){
var total = 0;
var maximum = 5;
var bt = document.getElementById('sub');
$.each($("input"),function(){
total += parseInt($(this).val()) || 0;
});
if(total > maximum){
bt.disabled = true;
}
else{
bt.disabled = false;
}
}
You need to run the function on change event of the inputs.
$(':input').on('change', assessSum);
function assessSum() {
var total = 0;
var maximum = 5;
var bt = document.getElementById('sub');
$("input").each((i, el) => {
total += (parseInt(el.value) || 0);
});
if (total > maximum) {
bt.disabled = true;
} else {
bt.disabled = false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>
The disabling can also be done like this:
$('#sub').attr('disabled', (total > maximum));

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

How do I enable a button when fields are filled in?

I'm trying to hide part of the form with the button disabled and have the user click on the button to show rest of form when previous fields are filled in. Can anyone help? Here's my code as an example:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1"/><br/>
<label>Field 2:</label>
<input type="text" class="field2"/><br/>
<label>Field 3:</label>
<input type="text" class="field3"/><br/>
</div>
<div align="center">
<button id="show_form" onClick = "this.style.display= 'none'" disabled="disabled">
Enter Billing Info</button>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
JQUERY
<script>
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
$("#show_form").prop("disabled", true);
$("#group2").hide();
$("#show_form").show();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
</script>
Try this jQuery:
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
/* This will hide the bottom form and disable the button again if
* any of the field above will be emptied.
* NOTE: This will just hide the form; it will not clear the fields.
*/
$("#show_form").prop("disabled", true);
$("#group2").hide();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
This will enable the button when all the fields in the initial form are filled. Then the user will be able to click on the button to see the rest of the form.
You just need to loop through each input and check if a value is set when the button is clicked like this:
$('#show_form').click(function () {
var fields = $('.js-field');
var pass = true;
for (var i = 0; i < fields.length; i++) {
if (!$(fields[i]).val()) {
pass = false;
}
}
if (pass === true) {
$('#group2').show();
}
});
I also needed to add some classes to your html:
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1 js-field"/><br/>
<label>Field 2:</label>
<input type="text" class="field2 js-field"/><br/>
<label>Field 3:</label>
<input type="text" class="field3 js-field"/><br/>
</div>
<button type="button" id="show_form" value="Show_Form">Enter Billing
Info</button>
<div id="group2" style="display: none;">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
To see it in action visit this fiddle.
You can add some logic to the click event and check all the input fields to have a value like this
$("#show_form").click(function(){
var allFilled = true;
$('#group1').find('input').each(function(){
//if someone is empty allFilled will keep false
if(this.value === ''){
allFilled = false;
//this breaks the each
return false;
}
});
if(allFilled){
$("#group2").show();
}
});
Keep in mind the previous code only work with input fields.

Validate input field, display error on submit and stop dialog open if error

I have a problem trying to validate my input field and alert the error, if number is below 50, i would like to know how to display an error popup (alert, or what ever), but to stop opening dialog modal if error occurred.
I did a script to force users write numbers below 50 with:
<script>
function handleChange(input) {
if (input.value < 50) input.value = 50;
if (input.value > 1000000) input.value = 1000000;
}
</script>
But once user type, for example: 23 and click on submit, it'll change the number in background to 50, but he would not be aware of that... What i can do about it?
Here's the full code i'm using:
<form id="testconfirmJQ" name="testconfirmJQ" method="post" onSubmit="return validator(users)" action="output.php">
<label>
<select id="selectUsers" class=" outtaHere" name="users" onChange='Choice();'>
<option value="0" selected="selected">Choose...</option>
<option value="1">Test</option>
</select>
</label>
<input type="hidden" id="ids" name="ids" >
<input type="hidden" id="use" name="username" >
<input type="hidden" id="ful" name="full_name" >
<p>
How much?
<input type="text" id="quantity" name="quantity" onchange="handleChange(this);">
<div style="font-size: 12px; float: left;">*Minimum quantity: 50</div>
</p>
<input id="submitJQ" name="submitJQ" type="submit" class="styled-button-1" value="Send" />
</form>
<div id="dialog" title="Potvrdite">
<div class="scroll-content">
<ul class="countrylist">
<img src="./images/png.png" class="vizitke"/>
</ul>
</div>
</div>
Thanks in advance...
<script>
function handleChange(input)
{
if (input.value < 50)
{
alert('your alert');
input.value = 50;
}
if (input.value > 1000000)
{
alert('your alert');
input.value = 1000000;
}
return false;
}
</script>
I this is what you are looking for
You can use this:
<script>
function handleChange(input) {
if (input.value < 50) {input.value = 50;alert("Your number is bellow 50!")}
if (input.value > 1000000) { input.value = 1000000;alert("Your number is above 1000000")}
}
</script>
Add an hidden input, whose default vale is false(means no error)
<input type="hidden" id="error" name="error" value='false'>
Then customize you js,
<script>function handleChange(input) {
if (input.value < 50) { input.value = 50; document.getElementById('error').value='true';}
if (input.value > 1000000) input.value = 1000000;}
function validator(user){
var error; error = document.getElementById('error').value; if(error == 'true'){alert('customize your alert error'); return false;} } </script>

Clear contents on click

In the following code:
<INPUT TYPE="radio" name="1" id="1" VALUE="1" <?php echo $checked1 ?>><font size="2">1</font>
<INPUT TYPE="radio" name="2" id="2" VALUE="2" <?php echo $checked2 ?>><font size="2">2</font>
<TEXTAREA name="names" id="names" rows="15" cols="65"><?php echo $names ?></TEXTAREA>
If the radio button 1 selected for the first time then onclick on textarea its contents should be cleared, but if the user clicks for the second time on the same text area the contents should not be cleared for the same radio button1.
The same should hold good for radio button2. How is this done?
This will fullfill your requirement. just place in body tag
<input type="radio" name="G1" id="1" value="1" /> <font size="2">1</font>
<input type="radio" name="G1" id="2" value="2" /> <font size="2">2</font>
<textarea name="names" id="names" rows="15" cols="65" onfocus="handleOnFocus()"></textarea>
<script type="text/javascript">
var isCleardForButton1 = false;
var isCleardForButton2 = false;
function handleOnFocus() {
var objTA = document.getElementById("names");
var objRadio1 = document.getElementById("1");
var objRadio2 = document.getElementById("2");
if (isCleardForButton1 == false && objRadio1.checked == true) {
objTA.value = "";
isCleardForButton1 = true;
}
if (isCleardForButton2 == false && objRadio2.checked == true) {
objTA.value = "";
isCleardForButton2 = true;
}
}
</script>
Demo and here is the code:
<TEXTAREA name="names" id="names" rows="15" cols="65" onclick="doIt(this);">Hello There</textarea>
<script>
var isDone = false;
function doIt(field)
{
if (document.getElementById("1").checked == true && isDone == false)
{
field.value = "";
isDone = true;
}
}
</script>
This would clear contents for the first time and not again for the life time of page.
edit: Looks like I mis-understood your requirements. This only applies to the click of the radio button, not to the textarea.
You need to setup a click event to clear the textarea content, and then unbind itself.
With jQuery the event handler would be something like:
$('#names').val('');
$(this).unbind('click');

Categories