How to bind change event dynamically in jquery - javascript

I am doing username availability check. I made jquery ajax call, its working fine and if username already in use i want to make label and textbox in red color. for this purpose i am adding css class in the callback function of $Post() method. The problem I have is css is not applying. I think the problem is in dynamically binding the event So please can any one help me in this. Here is my jquery script,
$(document).on('change', '#uName', function() {
var uName = $(this).val();//get the string typed by user
if (uName!=''){
$.post('<%=request.getContextPath()%>/controller/UserNameCheckController',{'uName':uName},
function(data) {
$('.status').html(data);
var status = $.trim($("#status").text());
if(status=="Username in use try another"){
$('#unameBlock').addClass('error');
}
});
}
else{
$('.status').html('');
}
});
Help me to fix this please. Thanks.

I think the error lies on your class selector
Change
$.trim($("#status").text());
to
$.trim($(".status").text());
//--------^-----------------

try changing it to
var status = $.trim($("#status").html());
it could be .status or #status depends upon the class or id you have used in your html.

Related

jQuery onclick event not works

I have a lot of buttons with specific class like this:
All of these buttons has stored JSON in data attribute. I've created function, where I detect clicked button, and do some stuff with this JSON like this:
$(".btn-load-road").on("click", function () {
console.log($(this).data("route"));
});
Click event is not fired. Can you tell me what is wrong with this?
You can use:
prop
method to get the value of data-route (JSON value)
Here's a quick solution. Hope it helps!
$(".btn-load-road").on("click", function () {
console.log($(this).prop("data-route"));
});
I see a problem in the quotation of the "data-route" value. You are trying to double-quot a string that is already doublequotted...
Instead of
data-route=""coordinates":[[18.159425,49.835919],...],"type":"LineString"}"
You could try single-quot the quoted strings inside your main string
data-route="{'coordinates':[[18.159425,49.835919],...],'type':'linestring'}"
See this working Fiddle

Trouble saving current state of css class in local storage

I am using two buttons to toggle css classes that either show or hide a background. I would like to save the current state of each class in local storage and display (or not display) them when the user returns. I have made an attempt with the wrapping class in this jsFiddle, but I don't have it working yet:
http://jsfiddle.net/eqrk6fak/1/
Setting it like so:
$("#switch2").click(function() {
wrap.fadeToggle(600);
if($('div').hasClass(wrap)){
localStorage.setItem('background', wrap);
}
});
And then trying to get it when the user returns:
$(document).ready(function(){
var background = localStorage.getItem('background');
if(background !== ''){
$('#wraping').addClass(background);
}
});
Any help would be appreciated. Thanks!
The problem is in the following line:
$('div').hasClass(wrap)
Reviewing your JSFiddle code, at that point wrap is a jQuery result:
var wrap = $(".wraping");
According to the documentation, jquery.hasClass receives a className which should be a String.

jQuery - How to aply custom CSS to fields which are not empty

I have some fields with class="required" which has custom css.
When i submit the form, i see an custom error message which aplies the required fields the css:
$(".required").addClass('required-fields');
Now, when i complete some fields (not all required) and i submit again de form, maybe what i need to see is: in the fields which have data (not empty), should go another css. Like border green or something like that.
Is it possible to do with a for maybe?
You could try something like this:
$('.required').removeClass('ok').filter(function(){
return !!$(this).val();
}).addClass('ok');
It filters all required fields with a value and adds class 'ok';
http://jsfiddle.net/cHPS2/
You can check if the input has a value. For example if($("#nameInput).value) will be true if its not blank. You can add a class to those inputs.
for(var i=0;i<inputs.length;i++){
if(inputs[i].value){
//enter add class code here
}
}
You have to pass on every input with a Jquery selector like
var $fields = $('.field');
And check if the field is required or not and if a value is given or not like :
$fields.each(function ($field) {
if ($field.hasClass('required') && !$field.value) {
$field.addClass('required-fields');
}
else {
$field.addClass('green-fields');
}
});
It's a rapid draft :)
Form validation with user feedback is a sufficiently common requirement that you may wish to consider using a plugin rather than coding a custom solution (reinventing the wheel) each time:
http://jqueryvalidation.org/documentation
You may try something like following (Can't be more pecific because you didn't provide HTML):
$('.required').not('[value=""]').css(...);
Using css() you may change the look of your elements.
Update:
To add a class to them try this:
$('.required').not('[value=""]').addClass('className');
To remove a class and then add another class (Also you may use toggleClass) try this:
$('.required').not('[value=""]').removeClass('className').addClass('className');
An Example.
Try this:
$('input.required:text').filter(function() {
return $(this).val() == "";
}).css(...);

Alternative method to display content

The selected radio button will show its corresponding dropdown box.
For example, upon the selected radio button ‘Ontario’, a dropdown box with matching cities will show up.
I have the following working code for the above example:
<script type="text/javascript">
$(document).ready(function(){
$("#searchForm input:radio").change(function() {
var buttonPressed = $('[name="Region"]:radio:checked').val();
var cityElmntBox = document.getElementById("dispalyCityBox");
if(buttonPressed == 'Ontario'){
cityElmntBox.style.display='block';
} else {
cityElmntBox.style.display='none';
}
});
});
</script>
Instead of the sudden effect (display='block'), I wanted to use for the selected elements the slideDown() method.
So I replaced:
cityElmntBox.style.display='block';
with:
cityElmntBox.slideDown(500);
But this doesn’t work…, please can someone help me get it working?
Wrap it in jQuery:
$(cityElmntBox).slideDown(500);
Also you can simplify the var statement like this and you wont have to put it in a wrapper:
var cityElmntBox = $("#dispalyCityBox");
Use $('#dispalyCityBox') instead of document.getElementById("dispalyCityBox").
Try $('#dispalyCityBox').slideDown(500) instead.
By using cityElmntBox.slideDown(500); you're trying to use a jQuery method on a non-jQuery object.

Passing parameters to jQuery function via link

I have a jQuery function:
$(function(){
function InitDialog(c,b){
/* some code */
}
$('a[name=dialog]').click(function(e) {
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
And also I have a link defined in html code like below:
<ul>
<li>something</li>
</ul>
My question is how can I pass the parameters (caption, bodyText) to Init() function via link?
I've heard about some method like below:
<li>something</li>
But I don't understand how can I get and parse it?
Thanks
Since you are using jquery, I would recommend that you do the following to store data on your element
Link Text
Then in your click function, you can access it as shown below
$('a#dialog').click(function(){
var me = $(this), data = me.data('params');
//console.log(data);
});
Edit - Fiddle added
Check the fiddle to see a working sample
using data-* attribute, you can:
<a name='dialog'
data-caption='this is the caption'
data-bodytext='this is the body'>klik</a>
and the javascript:
$(function() {
function InitDialog(c, b){
alert('the caption: ' + c);
alert('the body: ' + b);
}
$('a[name=dialog]').click(function(e) {
caption = $(this).data('caption'); // gets data-caption attribute value
bodyText = $(this).data('bodytext'); // gets the data-bodytext attribute value
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
tho instead of using name as the selector, i'd recommend class instead
So first, I think you want to say $('a[href="#dialog"]') to get the a tags, then in the click function, $(this).attr("name") will give you the some information, which you could store a json string...
My Text
$('a[href="#dialog"]').click(function() {
var data = JSON.parse($(this).attr("name"));
InitDialog(data.caption, data.bodyText);
});
But, I don't think that's the right way of going about what you're trying to do, would you be better to create the dialog in a div lower down the page, hide it, and only show it when you click the link? Because the term 'bodyText' implies it's going to be big...
Or just:
My Link

Categories

Resources