Using jQuery and HTML
When user clicks on button, I just want to put red border if value is empty. Otherwise do not put border.
Issue: first when you click on a button it works fine, but than if you enter a value, and hit button, than red border should be removed
$('.mybutton').click(function() {
if ($(".input").val().trim() == '')
$(".input").css('border-color', 'red');
else
$(".input").css('border-color', '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" name="fname1" class="input"><br>
<input type="text" name="fname2" class="input"><br>
<input type="text" name="fname3" class="input"><br>
<input type="text" name="fname4" class="input"><br>
<input type="submit" value="Submit" class="mybutton">
Since you have more than one .input class, you have to iterate through them and check whether each input has some value or not.
JSFiddle can works the way you expected.
$(function () {
$('.mybutton').click(function () {
$(".input").each(function () {
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
});
Loop each input after every click
Use .addClass() and .removeClass()
use this context to refer to current input to be evaluated if needed to add class or remove class
$('.mybutton').click(function() {
$(".input").each(function() {
if ($(this).val().trim() == '')
$(this).addClass('border');
else
$(this).removeClass('border');
})
});
.border {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" name="fname1" class="input"><br>
<input type="text" name="fname2" class="input"><br>
<input type="text" name="fname3" class="input"><br>
<input type="text" name="fname4" class="input"><br>
<input type="submit" value="Submit" class="mybutton">
You're currently selecting all inputs with your selector .input. When you do this and access the value it would return the value of the first selected element. (You'll notice that the highlighting works based on the value of the first input).
What you should instead do is iterate through the matched elements using .each and check the value/set style using this.
e.g.
$('.mybutton').click(function() {
$(".input").each(function() {
if (this.value.trim().length === 0)
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="text" name="fname1" class="input"><br>
<input type="text" name="fname2" class="input"><br>
<input type="text" name="fname3" class="input"><br>
<input type="text" name="fname4" class="input"><br>
<input type="submit" value="Submit" class="mybutton">
You should also have a look at the required attribute which is a much simpler way of displaying required fields.
You need to add an event handler for the input.
$('.input').on("input", function () {
if ($(".input").val().trim() == '')
$(".input").css('border-color', 'red');
else
$(".input").css('border-color', '');
});
You could go one step further and put this in a function.
Something like this
<script>
function validateInput() {
if ($(".input").val().trim() == '')
$(".input").css('border-color', 'red');
else
$(".input").css('border-color', '');
}
$(function () {
// The JQuery "on" function is generally preferred for
// attaching event handlers
$('.mybutton').on("click" ,validateInput);
$('.input').on("input", validateInput);
});
</script>
Related
newbie here. My target is when is when I click the button, my 2nd textbox will do the copy without comma. How can I make this work? I provided my JS fiddle and codes below. Any help will be appreciated. Thank you
JS Fiddle: https://jsfiddle.net/rain0221/auk4rfdg/6/ // I provided more explanation here
html:
<input type="text" value="" class="form-control" id="box"/>
<input type="text" value="" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
script:
//this function copies the textbox1 values with autocomma and produces same value but without comma on textbox2
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
//this function shows the value of my button to the textbox
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
}
When 5000 clicked, change textbox2 value!
Code snippet:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#box').on('keyup',function(){
updateTextView($(this));
});
});
$(document).ready(function(){
$("#bet4").on("click", function(e)
{
e.preventDefault();
let box = $("#box").val();
$("#betAmountResult").html(box);
})
})
function showme(count){
document.getElementById("box").value=count;
document.getElementById("textbox2").value=count.replace(',','');
}
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<input type="text" value="" class="form-control" placeholder="autocomma textbox" id="box"/>
<input type="text" value="" placeholder="same value but no comma" id="textbox2" required name="amount1" min="100" autocomplete="off"/>
<input id="bet4" class="amount btn btn-success" type="button" onclick="showme('5,000')" value="5000">
document.addEventListener("input", action)
document.addEventListener("click", action)
function action(ev){if (ev.target.tagName=="INPUT"){
const ch=ev.target.closest("div").children;
if(ev.target!=ch[1])
ch[1].value=(ev.target.value-0).toLocaleString()
if(ev.target==ch[2])
ch[0].value=ev.target.value;
}}
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="5000">
</div>
<div>
<input type="text" value="" class="form-control" required/>
<input type="text" value=""/>
<input class="amount btn btn-success" type="button" value="2000000">
</div>
I wrote my snippet without jQuery as it is not really needed here and I reversed the roles of the input fields as it is
a better user experience if the input is not tampered with directly
difficult to "undo" a .toLocaleString(), see here
The trigger for action is the input event which also includes paste actions done via mouse clicks.
I also removed the id attributes from your input values. This way you can add further input groups to your page and re-use the script without further change.
All my addEventListener() actions are done in the "delegated" mode, to the parent document. By doing it this way the event will also be triggered by dynamically added elements (elements that might get added through some user interaction).
I have 2 input fields one is enabled and one is disabled, on entering at least 6 characters in enabled field the second one (disabled field) should be enabled using javascript.
A different approach with an eventListener:
document.getElementById('enabled').addEventListener('keyup', function() {
if (this.value.length >= 6) {
document.getElementById('disabled').disabled = false;
} else {
document.getElementById('disabled').disabled = true;
}
});
<input type="text" id="enabled" placeholder="Type here...">
<input type="text" id="disabled" disabled>
$("#input1").keydown(function() {
if($(this).val().length > 6) {
$("#input2").attr('disabled', false)
}
});
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<form>
<input type="text" id="input1" />
<input type="text" id="input2" disabled />
</form>
To make this work you can use the input event handler on the first input, then use prop() to enable or disable the second input, based on the provided value.
It's possible to use keyup or keydown event handlers as an alternative, but be aware that they will not work when content is added or removed from the input using the mouse only.
Try this:
$('#enable').on('input', function() {
$('#disable').prop('disabled', $(this).val().length < 6);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputContainer">
<input type="text" id="enable" name="online-id" value="" class="focus sprite-clear_input_icns" placeholder="Online ID" />
</div>
<div class="inputContainer">
<input type="password" id="disable" class="masked" name="passcode" value="" placeholder="Passcode" disabled="true" readonly />
</div>
Use prop to enable disable your text with length.
$("#target1").keyup(function() {
var len = $('#target1').val().length;
if (len >= 6)
$("#target2").prop('disabled', false);
else
$("#target2").prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='target1' />
<input type='text' id='target2' disabled/>
I have a situation like the one below:
var value = document.getElementById("value").value;
if (value = 'a') {
('.setting').append('<input type="text" name="name" placeholder="carname">');
}
elseif(value = 'b') {
('.setting').append('<input type="text" name="name" placeholder="fruitname">');
}
$(document).ready(function() {
$("input[name=name]").keyup(function() {
alert("The text has been changed.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="username" placeholder="your name">
<select id="value"></select>
<div class="setting"></div>
The problem I have is that when I change the input the alert does not trigger. Does anyone know were am I messing up?
You're trying to select an input whose name property is "name", but the value you set in your HTML is name="username".
$(document).ready(function(){
$("input[name='username']").keyup(function(){
alert("The text has been changed.");
});
});
A better way yet is to give your input a unique id and select by that, so you don't have to use an attribute selector:
<input id="usernameInput" type="text" name="username" placeholder="your name">
$("#usernameInput").keyup(function(){ ... });
The $ is missing from ('.setting'), you should use .on to catch events of dynamically created elements and it's better to use it with classes, also use == or more likely === for conditions.
Live example
Your code modified:
<input type="text" name="name" class="example" placeholder="your name">
<select id="value"></select>
<div class="setting"></div>
<script>
var value = document.getElementById("value").value;
if(value==='a'){
$('.setting').append('<input type="text" name="name" class="example" placeholder="carname">');
}
else if(value==='b'){
$('.setting').append('<input type="text" name="name" class="example" placeholder="fruitname">');
}
</script>
<script>
$(document).ready(function(){
$('body').on('keyup', '.example', function() {
alert("The text has been changed.");
});
});
</script>
I have 10 input fields that I want to check have at least 2 charaters in ...
<input type="text" />
<input type="text" />
<input type="text" />
$('input[type="text"]').on('keyup', function(){
if($(this).length > 2){
alert('yeah')
} else {
alert('no');
}
});
I'm using the above but I keep getting the alert "No"
Why is this?
I'd just use this.value instead of making an unnecessary jQuery object. Also using the input event will make the logic fire only if the value changes, and not for other keys like arrow keys and others that don't actually change the value.
$('input[type="text"]').on('input', function(){
console.log(this.value.trim().length > 2 ? 'yeah' : 'no');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
<input type="text" />
$(this) refers to jQuery object, not element's value. You need to get the value first via $.val() method.
Do it like this:
if ($(this).val().length > 2) { ... }
http://api.jquery.com/val/
Or as #Taplar suggested, you can simply access the this.value property (this will refer to the first matched element). This way you can speed up the code a little bit because you will not create new jQuery object instance.
if (this.value.length > 2) { ... }
$('input[type="text"]').on('keyup', function(){
if($(this).val().length > 2){
console.log('yeah')
} else {
console.log('no');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
<input type="text" />
I have been looking at a few post on Stack trying to get a simple form validation working but all it does is disabled my submit button. Its meant to remove the disable once they've entered text inside the input field.
So Far
Jquery
$('input:submit').attr('disabled',true);
$('input').change(function(){
if($('input').val() != ''){
$('input:submit').attr('disabled',true);
} else {
$('input:submit').removeAttr('disabled');
});
HTML
<form action="send.php" method="post">
<input id="name" name="name" type="text" required placeholder="Name"/>
<input id="email" name="email" type="email" required placeholder="Enter a valid email address"/>
<input name="submit" id="subscribe" type="submit" value="Subscribe for free"/>
</form>
You should look for every input by using classes that are added to all fields that are requiered. If the user changes one of them and there is still no input, then the button while stay disabled:
jQuery:
$('input.required').change(function(){
if($(this).val() != ''){
$(this).removeClass('required',true);
}else{
$(this).addClass('required',true);
}
//check the length to enable or disable submit
if($(".required").length == 0){
$('#subscribe').attr('disabled',false);
}else{
$('#subscribe').attr('disabled',true);
}
});
html:
<form action="send.php" method="post">
<input id="name" name="name" type="text" class="required" placeholder="Name" />
<input id="email" name="email" type="email" class="required" placeholder="Enter a valid email address" />
<input name="submit" id="subscribe" type="submit" value="Subscribe for free" />
</form>
Here is a fiddle.
However keep in mind that this solution only works with javascript enabled.
I think you need to change your statements in if-else, let me know if you are trying something different apart from this--
$('input:submit').attr('disabled',true);
$('input').change(function(){
if($('input').val() != ''){
$('input:submit').removeAttr('disabled');
}else{
$('input:submit').attr('disabled',true);
}
});
Fiddle- http://jsfiddle.net/UcQhw/
Hey I have refined your code a bit, and its working as you intended
JS CODE:
$('#subscribe').attr('disabled',true);
$('input').change(function(){
if($('input').val() != ''){
$('#subscribe').attr('disabled',false);
}else{
//$('input:submit').removeAttr('disabled');
$('#subscribe').attr('disabled',true);
}
});
LIVE DEMO on JS Fiddle
happy Coding :)
Try Below code:
//$('input:submit').attr('disabled',true);
$('input').change(function(){
if($('input').val() != ''){ alert(1);
$('input:submit').attr('disabled',false);
}else{alert(2);
$('input:submit').attr('disabled', true);
}
});
Code: http://jsfiddle.net/WchJ9/
You got to swap statements in if-else block. Also use $(this) to get the source of event.
Live Demo
$('input:submit').attr('disabled', true);
$('input').change(function () {
if ($(this).val() !== '') {
$('input:submit').attr('disabled', false);
} else {
$('input:submit').prop('disabled', true);
}
});
if you want to check that all text field must not be empty then you have to iterate through all inputs. You should assign class to get sepecific textboxes instead of getting all on page. You can use class selector to get elements by class.
Live Demo
$('input:submit').attr('disabled', true);
$('.cls').change(function () {
blankFields = $('.cls').filter(function () {
return this.value == '';
});
if (blankFields.length === 0) $('input:submit').attr('disabled', false);
else $('input:submit').prop('disabled', true);
});