I'm trying to find a way that I can require two inputs to have text inside of them so I can toggle the disabled attribute on and off a button.
This would mean that when one input has text, the button is disabled. When both inputs have text, the button is enabled.
Here is my current code that I'm working with:
HTML:
<input name="e" placeholder="email">
<input name="p" placeholder="password">
<button id="submit_button" disabled>Submit</button>
JavaScript (no jQuery):
// Check if there is content in our form inputs and remove `disabled`
// from the button element.
var inputs = document.querySelectorAll('input[name="e"], input[name="p"]');
var button = document.querySelector('#submit_button');
[].forEach.call(inputs, function (e) {
e.addEventListener('input', function () {
// Set states for email and password inputs
if (this.value != "") {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
});
});
JSFiddle here
My thoughts with this code is that I would query the page for the two inputs, query for the button, and add an event listener that would check the input of each field, and when the value isn't empty, it would enable the button. Right now though, when you type something into either of the fields, regardless if both are filled in or not, the button becomes enabled.
How could I change this JavaScript so that both inputs must have text in order to enable the button?
How about this? :
var inputs = document.querySelectorAll('input[name="e"], input[name="p"]');
var button = document.querySelector('#submit_button');
[].forEach.call(inputs, function (e) {
e.addEventListener('input', function () {
var disabled = false;
[].forEach.call(inputs, function (inputElem) {
if(inputElem.value==''){
disabled = true;
}
});
// Set states for email and password inputs
if (disabled) {
button.setAttribute('disabled', '');
} else {
button.removeAttribute('disabled');
}
});
});
JSFiddle : http://jsfiddle.net/aecaaa9e/14/
Related
I need to enable the submit button as soon as all input fields has value enterred. I have two input fields type text and type password and a button which is disabled (I set its class as "disabled" than use CSS to change color etc..), I would like to remove that class whenever the above condition is met. I added 'change' and 'input' event listeners to all field like below:
const inputs = [...document.querySelectorAll('input[type="text"], input[type="password"]')];
const continueBtn = document.querySelector('continuebtn');
const signinForm = document.querySelector('#sign-in-form');
inputs.forEach((input) => {
input.addEventListener('input', function(e){
if (input.value !== '') {
continueBtn.classList.remove('disabled');
}else{
continueBtn.classList.add('disabled');
}
}
});
Tried with e.target.value.trim() === '' as well
I guess the above would be applied to all inputs and check if they're empty when the user is typing, but I'm not able to make it work: the button is being activated no matter what I do.
I would need some help in plain Javascript as this is what I'm currently learning. no jQuery. Thanks
Use the every() method to check all the inputs, not just the one that the user is currently editing.
const inputs = [...document.querySelectorAll('input[type="text"], input[type="password"]')];
const continueBtn = document.querySelector('#continuebtn');
const signinForm = document.querySelector('#sign-in-form');
inputs.forEach((input) => {
input.addEventListener('input', function(e) {
if (inputs.every(input => input.value.trim())) {
continueBtn.classList.remove('disabled');
} else {
continueBtn.classList.add('disabled');
}
});
});
#continuebtn.disabled {
background-color: grey;
}
<input type="text">
<input type="password">
<button id="continuebtn" class="disabled">Continue</button>
I want to set the focus in a single textbox and some text must be entered in the textbox to move the focus out of it. But there is an exception that I should be able click on the buttons on the page without any entry in that textbox.
Here is what I have done using JavaScript...
function Validate() {
var field1 = document.getElementById('<%=textbox.ClientID %>').value;
if (field1 == "") {
alert("Please Enter some value");
document.getElementById('<%=textbox.ClientID %>').focus();
return false;
}
else {
return true;
}
}
And I have called it like...
onblur="return Validate();"
This is the Script. (jquery required)
$(function() {
$('input[id=word]').blur(function() {
var txtClone = $(this).val();
if(txtClone=="")$(this).focus();
});
});
and here is a html tag
<input type='text' id='word' name='word'>
As you've asked, focus won't move away unless you entered some text and able to click on button outside.
i have disabled the submit button in my guestbook. it has 2 fields[name(textbox)&comment(textarea)].it has 2 other fields ID(primary key) and date.the function is:
function Frmvalidate() {
var nmchk=document.forms["guestform1"]["name"].value;
var cmntchk=document.forms["guestform1"]["comment"].value;
if (nmchk.length==0)
{
var namep = document.getElementById("namep");
namep.innerHTML="name must be filled out";
return false;
}
else if (cmntchk.length==0)
{
var cmntp = document.getElementById("cmntp");
cmntp.innerHTML="comment must be filled out";
return false;
}
else
{
document.getElementById("sbmt").disabled=false;
return true;
}
}
i have called the function in places: body tag's onload,button tag's onclick. still its not working and blank entries are being stored in my database.
You dont need to disable the submit button
you gain noting from it. ( alerting the user , running another script etc...)
instead -- The submit button should stop its regular behaviour by this code :
<input type="submit" onclick="return Frmvalidate();"/>
meaning :
when you press the button , it will execute the function yielding True or False and if it's True (only) it will continue to the server.
I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});
I'm doing some jQuery form validation and I came up with an issue. I have the following code so far:
// catch any form submission
$('form').submit(function () {
'use strict';
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required) {
// catch any field that should be required
$(this).find('input[required]').each(function () {
// if is empty
if ($(this).val() === '') {
// create a span that contains a warning to the user
var requiredFieldWarning = document.createElement('span');
requiredFieldWarning.text = 'This field is required.';
// display the span next to the current field
}
});
}
});
I'm trying to "attach" or display a span next to any input of the submitted form that doesn't validate, but I don't know how to. I want to do this unobtrusively, that's why I create the said span inside JavaScript.
Also, how can I prevent the form from being submitted if any of the fields of the submitted form doesn't validate?
why reinvent the wheel? you should use the jquery form validation plugin..
edit: added code to prevent submition of invalid form.
to answer your question:
$('form').submit(function (e) {
'use strict';
var valid = true;
var $form = $(this);
$form.find("span.error").remove();
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required) {
// catch any field that should be required
$form.find(':input[required]').each(function () {
// if is empty
var $this = $(this);
if ($.trim($this.val()) === '') {
// create a span that contains a warning to the user
$this.after("<span class='error'>This field is required.</span>");
valid = false;
}
});
}
if(!valid){
e.preventDefault();
}
});
here is a shorter version:
$('form').submit(function (e) {
'use strict';
Modernizr.input.required ? e[$(this).find("span.error").remove().end()
.find(':input[required][value=""]')
.after("<span class='error'>This field is required.</span>")
.length ? 'preventDefault': 'isDefaultPrevented']() : null;
});
I am adding a span tag after the input. Before the form is revalidated it removes these spans and recreates only if needed. If any of these spans are added the form isn't submitted.
$('form').submit(function (event) {
'use strict';
$('.invalid-error', $(this)).remove();
// remove any old spans
var submit_form = true;
// form submits by default
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required) {
// catch any field that should be required
$(this).find('input[required]').each(function () {
// if is empty
if ($(this).val() === '') {
$(this).after('<span="invalid-error">This field is required.</span>');
// add span after input
submit_form = false;
}
});
}
if(!submit_form) event.preventDefault();
// stop form from submitting
});
jsFiddle ( http://jsfiddle.net/4KxzB/10/ )
Here is my working example, works as expected in chrome.
To stop the form from submitting, just return false;
<form>
<input type="text" required/>
<input type="submit" value="submit"/>
</form>
<script>
$('form').submit(function ()
{
'use strict';
// if the browser doesn't support HTML5's required attribute
if (!Modernizr.input.required)
{
var validInput = true;
// catch any field that should be required
$(this).find('input[required]').each(function ()
{
// if is empty
if ($(this).val() === '')
{
// create a span that contains a warning to the user
var requiredFieldWarning = document.createElement('span');
requiredFieldWarning.text = 'This field is required.';
// Cancels form submit
validInput = false;
}
});
return validInput;
}
});
</script>
var flag = 0;
if ($(this).val() === '') {
flag = 1;
var warningblock = '<span class="warning">This field is required.</span>';
$(this).after(warningblock);
}
//end of each loop
if(flag){ //put this block out side the loop
return false; //form wont submit
}
return true;
CSS
.warning{
/**add styles for warning here***/
}