Specifiy input targeted blur function - javascript

My function works as it should. is there a way to remove the function from a specific input? Because it changes all inputs.. i have 2 check boxes and 1 input that i need to not have this function on.
$('input').blur(function(){
$('input').parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});

Try adding a class to the input and checkbox that you don't want the onblur functions, then update the code as below
Add the class to the three inputs that you don't want this feature
$('input').not( ".class" ).blur(function() {
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
Hope this helps what you need.

Use this context, $('input') will select all the <input> elements, this in the callback will hold the element on which event is invoked!
$('input').blur(function() {
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
.gray {
background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
<input type="text">
</div>
<div>
<input type="text">
</div>

If you have id's for those three inputs you can use this code snippet.
$('input').blur(function(){
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().not( "#id1, #id2, #id3" ).addClass("gray")
});
It will add class to those inputs which do not match the selector.

Related

Clear input, textarea on blur and default if field is blank

I am trying to clear two input fields with classes assigned, and one textarea with a class assigned of their default values on blur and return it to default only if the field is blank when the field is exited. If the user has included their own text I require that to stay.
This is what I have thus far:
$("input, textarea").focus(function() {
this.value = "";
});
$(".namefield").on("blur", function() {
$(this).val("Name");
});
$(".emailfield").on("blur", function() {
$(this).val("Email");
});
$(".messagefield").on("blur", function() {
$(this).val("Message");
});
First a quick note, the HTML placeholder attribute will do exactly what you describe natively. I'd encourage that as a first choice if possible. The implementation would simply be:
<input type="text" class="namefield" placeholder="Name" />
More reading on it is here: http://www.w3schools.com/tags/att_input_placeholder.asp
If you can't add attributes to the elements, but you have the value set, you can add the attributes dynamically using jQuery. You could use the jQuery method we talked about originally, or you could just add the placeholder attribute.
Here are both examples, I've also updated the JS Fiddle with a working example.
Using Placeholder
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).attr('placeholder',$(this).val());
$(this).val('');
})
})
Using data-default in conjunction with the original answer
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).data('default',$(this).val());
})
})
Original Answer:
If you still need to use jQuery, you can set and check the state and compare it against a default value. Something like this would work:
HTML
<input type="text" class="namefield" data-default="Name" value="Name" />
<input type="text" class="emailfield" data-default="Email" value="Email" />
JavaScript
$(document).ready(function() {
$("input, textarea").focus(function() {
if($(this).data('default') == $(this).val()) {
$(this).val('');
}
});
$("input, textarea").blur(function() {
if($(this).val() == '') {
$(this).val($(this).data('default'));
}
});
})
You can see it working in this JS Fiddle: https://jsfiddle.net/77Lk4kep/1/
Hope that helps!

onchange function to array of input text JQuery

Hello I have an array of input text they all have the same class, so I want to put an event OnChange with jquery to everyone of them.
My HTML code is:
<input type="text" class="form-control placementTest" data-mask=''>
and my Javascript is:
$('.placementTest').each(function() {
$(this).on('change',function (ev) {
alert('done it');
});
});
but it's not working. So, what is wrong?
No Need for $('.placementTest').each . Also, with an input, you want the keyup event Just need
$('.placementTest').keyup(function() {
//do stuff
})
or fire when the user leaves the input:
$('.placementTest').blur(function() {
//do stuff
})
Fiddle http://jsfiddle.net/qpu0Lsth/2/
your event must trigger after editing ( same on blur ).
if you need to trigger when user input something try to use about onkey "keydown" "keypress" "keyup" etc. . Example below !
$('.placementTest').each(function() {
$(this).on('keypress',function (ev) {
alert('done it');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
input 1 <input type="text" class="form-control placementTest" data-mask=''>
input 2 <input type="text" class="form-control placementTest" data-mask=''>
input 3 <input type="text" class="form-control placementTest" data-mask=''>
P.S. it's work fine !
Looks like you have two classes in the markup. Try to use one class

clear radio buttons when click on text input

I have a group of 4 radio buttons followed by a text input, when users click on the text input field I am trying to clear all radio inputs. here is my code so far.
<input type="radio" name="radio"><label for="radio1">1</label>
<input type="radio" name="radio"><label for="radio2">2</label>
<input type="radio" name="radio"><label for="radio3">3</label>
<input type="radio" name="radio"><label for="radio4">4</label>
<input type="text" id="textInput">
<script>
$('#textinput').click(function () {
radio.checked = false;
});
</script>
You can use .prop() to set checked property of input rabio buttons. Also you have misspelled textInput while event binding
<script>
$('#textInput').click(function () {
$('input[name="radio"]').prop("checked", false);
});
</script>
DEMO
<script>
$('#textInput').click(function () {
$('input[type=radio]').removeAttr("checked");
});
</script>
Or you can try attr() method
$('#textInput').click(function () {
$('input[name="radio"]').attr('checked',false);
});
DEMO
I think the best way to modify your script block (without changing your html) is first by ensuring that the code runs on document ready, and also you should probably ensure that the event is focus, not click, in case someone is using a keyboard or alternate navigation:
$(function() {
$('#textInput').focus(function () {
$('input[name=radio]').prop("checked", false);
});
});
Though it's probably more likely that you want to only clear other selections if they actually enter some data in that field, you might want to instead do:
$(function() {
$('#textInput').on('input', function () {
if($(this).val().length > 0) {
$('input[name=radio]').prop("checked", false);
}
});
});

Change the div color on input focus

What am trying is to change the color of the div with letter s
<div class="search_container">
<input type="text" class="search_field" placeholder="Search..." />
<div id="magnify_glass">s</div>
</div>
What I tried is this
<script>
$('.search_field').focus(function() {
$('#magnify_glass').css('color','#ff0000');
});
</script>
Assuming your code is in the <head> of the document, you just need a document ready handler. Try this:
Update
To remove the colour you need to add a blur handler too.
<script>
$(function() {
$('.search_field').focus(function() {
$('#magnify_glass').css('color','#ff0000');
}).blur(function() {
$('#magnify_glass').css('color','transparent'); // or whatever the default is.
});
});
</script>
Also, it's better to use a class to add styling to an element as it's a better separation of concerns:
.focus { color: #F00; }
$('.search_field').focus(function() {
$('#magnify_glass').addClass('focus');
}).blur(function() {
$('#magnify_glass').removeClass('focus');
});
You code is fine and working you need to ensure you have the code in document.ready to ensure the element availability before accessed by script and you have jquery library added.
Live Demo
$('.search_field').focus(function () {
$('#magnify_glass').css('color', '#ff0000');
}).blur(function() {
$('#magnify_glass').css('color', '#000000');
})

jQuery checkbox checked state changed event

I want an event to fire client side when a checkbox is checked / unchecked:
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
// Do stuff
}
});
Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
Bind to the change event instead of click. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the change event over the click event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change event. Redacted in comments
Also note that I've used this.checked instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');
$postList.find('h1').on('click', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000);
setTimeout(generateRandomArticle.bind(null, ++title), 5000);
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
While this example displays the usage of event delegation to capture events for a specific node (h1 in this case), and issue a callback for such events.
$postList = $('#post-list');
$postList.on('click', 'h1', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
Just another solution
$('.checkbox_class').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
// do the magic here
}
})
If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.
$(function() {
$("input[type='checkbox']:checked").change(function() {
})
})
if your intention is to attach event to all checkboxes (checked and unchecked)
$(function() {
$("input[type='checkbox']").change(function() {
})
})
if you want it to fire only when they are being checked (from unchecked) then #James Allardice answer above.
BTW input[type='checkbox']:checked is CSS selector.
Is very simple, this is the way I use:
JQuery:
$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
var checkbox = $(this), // Selected or current checkbox
value = checkbox.val(); // Value of checkbox
if (checkbox.is(':checked'))
{
console.log('checked');
}else
{
console.log('not checked');
}
});
Regards!
$(document).ready(function () {
$(document).on('change', 'input[Id="chkproperty"]', function (e) {
alert($(this).val());
});
});
This is the solution to find is the checkbox is checked or not.
Use the #prop() function//
$("#c_checkbox").on('change', function () {
if ($(this).prop('checked')) {
// do stuff//
}
});
It can also be accomplished as below. When the checkbox is fired, the div
or control with #checkbox id is hiddden or is shown otherwise.
<script>
$('#checkbox').on('click',function(){
if(this.checked){
$('#checkbox').hide();
}else{
$('#checkbox').show();
}
});
</script>
Action taking based on an event (on click event).
$('#my_checkbox').on('click',function(){
$('#my_div').hide();
if(this.checked){
$('#my_div').show();
}
});
Without event taking action based on current state.
$('#my_div').hide();
if($('#my_checkbox').is(':checked')){
$('#my_div').show();
}
Try this "html-approach" which is acceptable for small JS projects
function msg(animal,is) {
console.log(animal, is.checked); // Do stuff
}
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
perhaps this may be an alternative for you.
<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`
Try this jQuery validation
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
rules: {
agree: {
required: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<form id="myform" action="" method="post">
<div class="buttons">
<div class="pull-right">
<input type="checkbox" name="agree" /><br/>
<label>I have read and agree to the Terms of services </label>
</div>
</div>
<button type="submit">Agree</button>
</form>
the key is: use prop but not attr to query the checked status, e.g.
correct: jQuery('#my_check_tag').prop('checked') // return correct status
incorrect: jQuery('#my_check_tag').attr('checked') // always return undefined

Categories

Resources