JQuery functions declaration and reusing it - javascript

I've got the following jQuery code
$('#rta_ad_yes').click(function(){
$('#rta_ad_pref, #rta_ad_psn').prop('disabled', false);
$('#div_ad_pref, #div_ad_psn').addClass('has-warning');
});
$('#rta_fp_yes').click(function(){
$('#rta_ad_fpref, #rta_ad_fpsn').prop('disabled', true);
$('#div_ad_fpref, #div_ad_fpsn').addClass('has-warning');
});
If you look at the above code it seems i'm doing same coding to achieve the same result.. $('#rta_ad_yes') and $('#rta_fp_yes') in two different pages
sorry to not mentioning my question question how can i declare and call that function provide parameters rather than typing the whole thing again and again.. i dont know how to declare function and reuse it in jquery not very good at jquery

you can try the following code.
function isEmpty (test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-warning');
return false;
}else{
element.removeClass('has-warning');
return true;
}
};
and reuse that like below
var x = isEmpty($('#rta_cl_fn'), $('#div_cl_fn'));
hope that helped

Try
.split()
$('#rta_ad_yes', '#rta_fp_yes').click(function () {
var id = (this.id.split('_')[1] == 'fp')? 'f' : '';//get ad or fp from id
//if it's `fp` than add `f` if not than empty string .
$('#rta_ad_' + id + 'pref, #rta_ad_' + id + 'psn').prop('disabled', function(){
return id.length;//return false if 0 and for 1 return true .
}); //make id out of it
$('#div_ad_' + id + 'pref, #div_ad_' + id + 'psn').addClass('has-warning');
});

I believe you want to abstract that in a function?
var disableAndWarn = function (config) {
$("#" + config.id1 + ', ' + "#" + config.id2).attr('disabled', 'disabled');
$("#" + config.id3 + ', ' + "#" + config.id4).addClass('has-warning');
}
Here is a FIDDLE
Edit: Changed your .prop('disabled', true) into .attr('disabled', 'disabled') since I believe that's what you intended.

Related

See if there is a form inside a div

I have a div with an id like: comment-box-5 and I want to see using javascript if there is a form inside of it if so remove it if not add it (so it toggles when I call the function). I wrote this piece of code to try to do this:
function reply(id){
console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id)));
if (document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))) {
var form = replyFn(id);
document.getElementById('comment-id-' + id).appendChild(form);
} else {
//for toogle effect
document.getElementById('comment-id-' + id).removeChild(document.getElementById("form-" + id));
}
}
And I tried executing it but console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))); prints -1 even if there is a form inside.
What am I doing wrong? how can I actually see if there is a form in the div?
You could change your condition to :
if ( document.querySelector('#comment-id-' + id +'>#form-' + id) ) {
//Your if logic
}else{
//Your else logic
}
Snippet :
var id = 1;
if (document.querySelector('#comment-id-' + id + '>#form-' + id)) {
console.log('Remove form');
} else {
console.log('Add form');
}
<div id="comment-id-1">
<form id="form-1"></form>
</div>
Try using contains on the div without innerHTML like below, I changed the code from yours a bit to do the example but it should work for yours as well.
console.log(document.getElementById('comment-id-1').contains(document.getElementById('form-id-1')));
<div id="comment-id-1"><form id="form-id-1"></form></div>

Textarea value remain the same after submitting a form

My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable

jQuery: Trimming not working for checking empty inputs

I'm using $.trim to check if the inputs are empty, if so, nothing should happen. If they're not empty then the form should be submitted.
This is the variable where the condition is located:
var save = $("<input type='button' value='Save' />").on('click',function() {
if(!$.trim(name)==''||!$.trim(degree)==''||!$.trim(dateFrom)==''||!$.trim(dateTo)=='') {
$("#list").append("<li>Name: "+$('#elem1').val()+
"<br>Degree: "+$('#elem2').val()+
"<br>Date From: "+$('#elem3').val()+
"<br>Date To: "+$('#elem4').val()+
"</li>");
cancel.click();
} else {}
});
Please take a look to the code on jsFiddle here: http://jsfiddle.net/vrpWu/
Click on "Add another"
Note that it works without the if condition, why is this happening? I've readed everywhere but looks like my code is not wrong.
First, you have to get the values when you actually click the save button, not before, as then the values will always be empty strings
var save = $("<input type='submit' value='Save' />").on('click', function () {
var name = $("#elem1").val();
var degree = $("#elem2").val();
var dateFrom = $("#elem3").val();
var dateTo = $("#elem4").val();
if (!($.trim(name) == '' || $.trim(degree) == '' || $.trim(dateFrom) == '' || $.trim(dateTo) == '')) {
console.log('test')
$("#list").append("<li>Name1: " + $('#elem1').val() +
"<br>Name2: " + $('#elem2').val() +
"<br>Name3: " + $('#elem3').val() +
"<br>Name4: " + $('#elem4').val() +
"</li>");
cancel.click();
} else {
console.log('no')
}
});
then you should note that things work a little differently when you negate the variables and use OR
You can either negate the whole thing at once
if (! ($.trim(name)==''||$.trim(degree)==''||$.trim(dateFrom)==''||$.trim(dateTo)=='')) {
or use AND instead
if (!$.trim(name)=='' && !$.trim(degree)=='' && !$.trim(dateFrom)=='' ... etc
FIDDLE

how to store multiple values of dynamically appended elements into a single var and retrieve then into a function

How can I store multiple values into a single variable and retrieve them into a setTimeout function.
$(document).ready (function (){
div ({'div':'#noo','auto':'true','pos':'top','txt':'hello'});
div ({'div':'#bottom','auto':'true','pos':'bottom','txt':'hi'});
setTimeout (function (){div ({'div':'#top','pos':'top','auto':'true','txt':'new'});}, 4000);
});
function div(obj) {
obj.div; obj.auto; obj.pos; obj.txt; obj.time;
var rec = {};
if(obj.pos == 'top') { $('<ul id="top"></ul>').appendTo('body'); }
if(obj.pos == 'bottom') { $('<ul id="bottom"></ul>').appendTo('body');
$(obj.div).append('<li data-name="' + $.now() + '">' + obj.txt + '</li>');
if(!obj.time) { obj.time = 6000; }
if(obj.auto == 'true') {
setTimeout(function () {
$(obj.div + ' li').fadeOut();
}, obj.time);
}
}
Now, how can I store "data-name" into "rec" variable and retrieve them into setTimeout function for hiding them when "obj.time" is over.
Your code has some mistakes in using jquery selectors. please use # to access by ID
$("#"+obj.div).append('<li data-name="' + $.now() + '">' + obj.txt + '</li>');
also in setTimeout
$("#"+obj.div + ' li').fadeOut();
I am confused in closing brace of second if condition. I closed in that line and its working fine. if you want to retrieve "data-name" to rec, you can use
$("#"+obj.div + ' li').each(function(i) {
$(this).attr('data-name');
});
for single or multiple values. also you can pass to setTimeout as a parameter.
http://arguments.callee.info/2008/11/10/passing-arguments-to-settimeout-and-setinterval/

How to access id attribute of any element in Raphael

I'm using Raphael for drawing some elements on a website. The elements include rectangle, line (path). I have given an id to the path element and trying to access it in the onclick event of that line. but when I do an alert of the id, nothing is visible. Following is the code snippet
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
t.node.onclick = processPathOnClick;
}
function processPathOnClick()
{
alert($(this).attr("id"));
}
Can anyone please tell me what is the problem with the above code. Any pointer will be helpful.
Thanks
Are you sure you don't want to write $(t.node).attr('id','Hello'); instead?
Update: someone just downvoted this answer. And I truly feel obligated to point out this way of setting the id isn't particularly good. You would be better off using:
t.node.id = 'Hello';
I wish there was a way to credit Juan Mendes, other than upvoting his comment to this answer.
Try this:
function createLine() {
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.id = 'Hello';
t.node.onclick = processPathOnClick;
}
function processPathOnClick() {
alert($(this).id);
alert(this.id); // This should work too...
}
Basically you are creating a new property called "id" on your Raphael line instance variable "t". It's kind of hacking, in my opinion, but it does the trick just fine.
Try setting the handler using jquery
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
$(t.node).click(processPathOnClick);
}
function processPathOnClick()
{
alert($(this).attr("id"));
}

Categories

Resources