Javascript disable input field - javascript

I have two input fields one is for a phone number another is for an email. I would like to disable one field based on the user selection. Should a user click and enter input in either field, it would disable the other and vice versa.
I have written code but it seems to only disable the email field upon entering in numbers in the phone field. Removing the numbers in the phone field removes the disabled from the email input field.
IN MY HTML
<input type="number" name="number" placeholder="hone" class="cellphone" data-cp-visibility="new-user" id="phone">
<input type="email" name="email" placeholder="enter email" class="email" data-cp-visibility="new-user" id="email">
IN JAVASCRIPT
$('#phone').live('blur',function(){
if(document.getElementById('phone').value > 1) {
$('#email').attr('disabled', true);
} else {
$('#email').attr('disabled', false);
}
});
$('#email').live('blur',function(){
if(document.getElementById('email').value > 1) {
$('#phone').attr('disabled', true);
} else {
$('#phone').attr('disabled', false);
}
});
Ultimately I what I am trying to accomplish is that a user can click in either field and then enter input, upon doing so, the other field is disabled. Should they choose to remove the text they entered, it would remove the disabled feature and then they could choose the opposite input field.
I am not sure why it only works for one field and not the other or why if you enter in 333-333-3333 in the phone field it breaks the disabled, but 33333333 works fine.
Any ideas or insight as to what I may be missing?

to fix the dash issue you are having with the phone input, you can try changing it to:
<input type="text" required="" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="phone" id="phone" data-cp-visibility="new-user" placeholder="123-345-5678">
and here is another version of the js:
var $phone = $('#phone'),
$email = $('#email');
$phone.on('keyup change', function() {
$email.prop('disabled', $(this).val() ? true : false );
});
$email.on('keyup change', function() {
$phone.prop('disabled', $(this).val() ? true : false );
});

You may use jQuery on instead of live. live is deprecated as of jQuery 1.7.
You can also look for the keyup/keydown event on the input element.
$(function(){
$('#phone').on('keyup',function(){
if($(this).val()!=="")
{
$('#email').prop('disabled', true);
}
else {
$('#email').attr('disabled', false);
}
});
$('#email').on('keyup',function(){
if($(this).val()!=="")
{
$('#phone').prop('disabled', true);
}
else {
$('#phone').prop('disabled', false);
}
});
});
Here is a working sample.

I would recommend using .on('input', ...) to listen for changes, this makes it so even if you use the increment/decrement buttons (or other forms of input) you'll trigger the event-handler. Then use .attr('disabled', boolean) to control enable/disabled state, see example below:
$(function() {
$('#phone').on('input', function() {
$('#email').attr('disabled', $(this).val() !== "");
});
$('#email').on('input', function() {
$('#phone').attr('disabled', $(this).val() !== "");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" placeholder="phone" id="phone">
<input type="email" placeholder="enter email" id="email">

Related

Regex email validation on submit

I want to do a very basic jQuery validation of an email via a regex on submit. My HTML:
<form action="POST" id="form">
<input type="email" id="customer_email" placeholder="email here" />
<input type="submit" />
</form>
JS:
$('#form').submit(function() {
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').value();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
To my understanding, for this to work I need to get the value of the input via email input (which I do on line 4) and run a regex on it.
When submit is clicked, the standard input error appears on the form, and not the window alert. Feel free to view a Codepen outlining this here:
http://codepen.io/anon/pen/oYmJLW?editors=1010
You need to add event.preventDefault() to prevent the actual form submission, and use .val() instead of .value() on the input.
$('#form').submit(function(event) {
event.preventDefault();
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').val();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
By declaring your input as type="email" your browser will do the validity checking (you don't need to do it yourself then), if you want to circumvent that use type="text".

Input text validation using jQuery

I have a situation where i want to validate the text entered into a input text field. This is the HTML code:
<div id="err_title" style="display:none;">Please enter a valid Number.</div>
<input type="radio" id="txt_a-radio" value="valueA" checked="checked">
<input type="text" id="txt_a">
<input type="radio" id="txt_b-radio" value="valueB">
<input type="text" id="txt_b" disabled>
By default #txt_b field will be disabled, when user clicks on #txt_b-radio button #txt_b will be enabled and #txt_a will be disabled.
The condition for validation is:
#txt_a can contain only 12 digit number
#txt_b can contain only 20 digit number
Validation should happen once user enters value in enabled field then clicks anywhere outside. If value entered by user is not valid error message #err_title should display.
Suppose if user enters value for #txt_a and then clicks on #txt_b-radio button then validation shouldn't happen since user has switched the input field.In this case #txt_a should be disabled and txt_b enabled.
I have tried with the following code:
$('#txt_a').change(function() {
custNumber = $('#txt_a').val(); expression = /^[0-9]{12}$/;
if(custNumber === '') {
$("#err_title").css('display', 'none');
} else if ((!custNumber.match(regexp))) {
$("#err_title").css('display', 'block');
} else {
$("#err_title").css('display', 'none');
}
});
$input1 = $('input[name="input1"]');
$input2 = $('input[name="input2"]');
$checkbox = $('input[name="checkbox"]');
$input1.on('change', function(e) {
var isValid = this.value.length >= 12;
this.classList.toggle('notValid', !isValid);
})
$checkbox.on('change', function(e) {
$input2.prop('disabled', !this.checked);
})
input.notValid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input1" />
<input type="text" name="input2" disabled />
<input type="checkbox" name="checkbox" />
NOTE:
In example above, I'm mixing vanillia JS, with jQuery. I would recommend avoiding it - I did that to show You how easy (well not always...) it is to do such a simple thing without jQuery.
Basically, if You want to do simple stuff like that, I would recommend to give up on jQuery.
ANSWER:
You are looking for jQuery change event. It triggers once input loose focus.
$(your_input).on('change', function(e) {...} )
You can validate input length like (function inside listener) :
var isValid = this.value.length === 12
Same goes with disabled/enabled input.
You have to attach event listener to checkbox
$(your_checkbox).on('change', function(e) {...} )
then You can get state of checkbox :
var isChecked = this.checked
and disable/enable Your input
$(your_input).attr('disabled', !isChecked)

Prevent unallowed pasting into text-input

I'm trying to prevent the user from pasting unallowed text into an input field. The Input is a randomly generated 8 digit Code, that contains letters and numbers.
But I don't want the user to paste any text that contains other characters.
my input field:
<input type='text' id='form-code-field' name='code' maxlength='8'>
Note:
I'm not looking for something like the readonly attribute, because the user still has to input alphanumeric text into the field.
You could test value input using a regex on input event:
$('#form-code-field').on('input', function(){
if(!/^[a-z0-9]+$/i.test(this.value)) this.value = $(this).data('oldValue') || "";
else $(this).data('oldValue', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='form-code-field' name='code' maxlength='8'>
For HTML5 browsers you can also do this, and no script required:
<input type='text' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9">
This will not stop someone from write non valid characters, the pattern will be evaluated on submit and will abort the submit with a message if not matched.
Update
I added a plain javascript version for those who don't use jQuery, which works globally on a form. Just set the "pattern" on a input field and it kicks in.
The script also works on input on non HTML5 browsers.
A "safety" note:
As a client side evaluation, this by no means is 100% safe to just store server side, you always need to check whats posted before doing anything with it.
document.getElementById('form').addEventListener('input', function(e){
if (e.target.pattern && e.target.pattern.length > 0) {
var regex = new RegExp(e.target.pattern,"i");
if(!regex.test(e.target.value)) {
if (e.target.value.length > 0) {
e.target.value = e.target.getAttribute('data-old-value') || "";
} else {
e.target.setAttribute('data-old-value', "");
}
} else {
e.target.setAttribute('data-old-value', e.target.value);
}
}
}, false);
<form id="form">
Only alphanum (max 8): <input type='text' id='form-code-field' name='code' maxlength='8' pattern="^[a-z0-9]+$" title="a-z0-9"><br /><br />
Any character (max 5): <input type='text' id='form-code-field' name='code' maxlength='5' ><br />
</form>

check if all input field has value jQuery condition

i have several input fields with a class name of required.
i have a code below to check if all my <input> fields have a value, if not empty or null, it will show/unhide a specific div.
but it doest seem to work on me.
also, by default, #print is displayed as none via CSS.
<!-- index.php -->
<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<!-- script.js -->
$(document).ready(function() {
$('input.required').each(function() {
if($(this).val() != "") {
$("#print").show();
}
else {
$("#print").hide();
}
});
});
I'd suggest:
$('#print').toggle(!($('input.required').length == $('input.required').filter(function () {
return this.value;
}).length));
Simplified JS Fiddle demo.
Obviously this should be run on submit, assuming you want to only show the #print element as a validation prior to submission.
References:
filter().
toggle().
As I stated in my comment above, you're checking the values when the page loads, before the user has any chance to enter anything. If you have a button on your page, bind the event to that which will fire the function at the right time.
Something a little like this jFiddle
index.php
<input type="text" id="getID" class="required form-control" placeholder="id">
<input type="text" id="getName" class="required form-control" placeholder="name">
<div id="button">Submit</div>
<div id="print">You're missing something D:!</div>
script.js
$('#button').on('click', function() {
$('#print').hide();
var error=false;
$('input.required').each(function() {
if($(this).val() == "") {
error=true;
}
});
if(error) {
$('#print').show();
}
});
Try
$(document).ready(function () {
//the default state
var valid = true;
$('input.required').each(function () {
//if the value of the current input is blank then the set is invalid and we can stop the iteration now
if ($.trim(this.value) == '') {
valid = false;
return false;
}
});
//set the visibility of the element based on the value of valid state
$("#print").toggle(!valid);
});

Cursor appear on search box click

Just want some direction really.
Want my search box to have text inside, but when it is clicked, it clears it and allows the user to start typing.
How is this achieved?
jQuery?
Anyone got any useful links or tips to do this?
Thanks :)
Update for 'jQuery'
<form action="process.php" method="POST">
<input type="text" name="keyword" value="Keyword or code" id="textBox"/>
<?php echo $form->error("keyword"); ?>
<input type="submit" value="Search" name="search" />
</form>
<script type="text/javascript">
$('#textBox').focus(function() {
if ($(this).val()==='Keyword or code') {
$(this).val('');
}
});
$('#textBox').blur(function() {
if($(this).val()==='') {
$(this).val('Keyword or code');
}
});
</script>
A more generic approach (we do not need to have the watermark text in the JS):
Given the HTML element <input class="watermark" type="text" value="Text Here" />
And the following Javascript:
<script type="text/javascript">
$(document).ready( function () {
$('input.watermark').focus( function () {
var $this = $(this);
if( !$this.data('watermark_value') || $this.data('watermark_value') === $this.val() ) {
$this.data( 'watermark_value', $this.val() ).val( '' );
}
});
$('input.watermark').blur( function () {
var $this = $(this);
if( $this.val() === '' ) {
$this.val( $this.data('watermark_value') );
}
});
});
</script>
Then you can give any input the class watermark to get the effect.
This will store the original value of the input and make the input blank when first entered, if the field is left blank when focus is removed it'll put the original value back, if the user enters a value into the input then nothing will happen when they leave. If they later revisit the input and make it blank, then again the original value will be inserted.
jQuery isn't necessary - here's a simple plain Javascript solution.
You need to bind to the inputs onfocus event and restore your default with the onblur if it was left empty:
function initSearchBox() {
var theInput = document.getElementById('idOfYourInputElement');
// Clear out the input if it holds your default text
if (theInput.value = "Your default text") {
theInput.value = "";
}
}
function blurSearchBox() {
var theInput = document.getElementById('idOfYourInputElement');
// Restore default text if it's empty
if (theInput.value == "") {
theInput.value = "Your default text";
}
}
<input type='text' value="Your default text" onfocus="initSearchBox();" onblur="blurSearchBox();" />
Actually by this method, it's not really even necessary to getElementById(). You can probably just use this.
try this:
HTML:
<input id="searchBox" value=""/>
JQUERY:
var pre = $('#searchBox').val();
$('#searchBox').focus(function() {
if($(this).val() != pre)
$(this).val($(this).val());
else
$(this).val('');
}).blur(function() {
if ($(this).val() != null && $(this).val() != '')
$(this).val($(this).val());
else
$(this).val(pre);
}).keyup(function() {
if ($(this).val() == null || $(this).val() == '' || $(this).val() == undefined)
$(this).val(pre).blur(); // here the input box will lost cursor blink until you click again due to `blur()` function
});
This can be done with jQuery using the following method;
HTML;
<input id="textBox" name="" type="text" value="text here" />
The jQuery;
$('#textBox').focus(function() {
if ($(this).val()==='text here') {
$(this).val('');
}
});
$('#textBox').blur(function() {
if($(this).val()==='') {
$(this).val('text here');
}
});
This will remove the value of the text box if it is current "text here", then if the user clicks off the box and leaves it empty, it'll add the placeholder text back in.
You could change the .focus to simply be a click function to remove any content, regardless of what's in there.
$('#textBox').click(function() {
$(this).val('');
});
Or you can just use some Javascript in the Input field in HTML like so;
<input type="text" value="Text here" onfocus="if(this.value=='Text here')this.value='';" onblur="if(this.value=='')this.value='Text here';" />
Again, this will only remove text on click if the value is "text here" and it'll add "Text here" back in if the user leaves the box empty.
But you could adjust the onfocus to remove any content with;
<input type="text" value="Text here" onfocus="this.value='';" onblur="if(this.value=='')this.value='Text here';" />
Ensure you've got jQuery included, add this in the ....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
You can do this in html5 like this:
<imput type="search" value="" placeholder="search here">
But support in IE is limited.
Or, you can do it with jquery very easily:
$(function() {
$("#search").click(function() {
$(this).val("");
});
});
You can just add placeholder="" into your input tag
<input type="text" placeholder="Keyword or code">
This will generate a watermark which goes away when you focus on it

Categories