Setting the HTML property of an element in jQuery - javascript

Please check the codes..
$(".editable").live("click",function(){
CurrentOBJhtml = $(this).text();
nextHtml = "<input type='text' class='hoverable' value='"+CurrentOBJhtml+"' />";
var c = nextHtml;
alert(c); //here two alert box comes....
$(this).html(c);
});
When i alert c ,it alerting two values in two alert boxes...
first value is <input type='text' value='myname' class='hoverable' />
second one is <input type='text' value='' class='hoverable' /> where the second one doesnt have the value .
When i comment the last line ($(this).html(c);) then it only giving the first result.
What is the problem with me ? i am totally confused.
please help me to solve this issue.
Thank you .
Update :
HTML :
<fieldset id="user_info_module">
<label>username:</label>
<label class="editable" id="user_info_username">
<label>Email:</label>
<label id="user_info_email"> </label>
<label>Default page:</label>
<label id="user_info_defaultpage"></label>
<label>mobile:</label><label id="user_info_mobile"></label>
<label>country:</label><label id="user_info_country"></label>
<label>address:</label><label id="user_info_address"></label>
<label>pincode:</label><label id="user_info_pincode"></label>
<label>landline:</label><label id="user_info_landline"></label>
</fieldset>
http://jsfiddle.net/M3J2p/1/

First thing put your jquery code inside the $(document).ready(function()); handler.
and check this jsfiddle, it is not showing any double alert box to me. when you click a element then this will refer to that particular element not the others.
Update your html code in question to confirm about the exact problem or create a example jsfiddle for your problem.
Edit: Error reasons and solved
Before jQuery 1.7, to stop further handlers from executing after one
bound using .live(), the handler must return false. Calling
.stopPropagation() will not accomplish this.
$("a").live("click", function(event){
event.preventDefault();
});
Check your updated jsfiddle as per your code. you have missed to close the one tag and the above event bubbling problem occurs when you use this. In updated jquery use .on() ..
check .live() documentation at jQuery to konw about this better.

May be you have two elements with the class "editable" or that you calling the code above twice. Do you have it in document.ready? or calling it through function?

I suppose that $(".editable") finds more than one element. If you want to find a specific element, consider using the Id or you can also check whether the target is the correct one in the callback.
$(".editable").live("click",function(event)
{
if (event.target == mytarget)
{
// do something
}
});

Related

Whats the difference between $(e.target).find and template.find('input').value

Its probably something basic but wanted explanation of the use cases. Like sometimes hitting "enter" inputs the data, while sometimes mouseclicks work. I'm concerned about "Gotchas" that I would have overlooked. Like maybe it works in Firefox but not in Chrome for example.
I saw the following 2 ways, both are ways to input data into a form element.
First way
JavaScript
var $body = $(e.target).find('[name=body]'); //defines the content
var comment = { body: $body.val() };
HTML
<form class="form-send-message" id="addcomment" data-keyboard-attach>
<textarea id="body" name="body"></textarea>
</form>
Second way
JavaScript
var message = template.find('input').value;
HTML
<form class="message" data-keyboard-attach>
<input type="text" name="body" id="body">
<button class="icon" type="submit"></button>
</form>
Here you can see two ways to find the value of an input/textarea with an explanation:
'submit .new-post': function(event){
//returns name="postBody" content from the form you're submitting
var postBody = event.target.postBody.value;
//returns the value of an html element that exists in DOM, even if its inside a different template or form.
var postBody = $('.someClass').val()
}
Your first code Is jQuery, while your second code is Meteor. They both can accomplish the same thing under the right circumstances. Also, according to this answer, meteor's template.find is an alias for jQuery's $, meaning they are the exact same.
But, the codes don't do the same thing in this case.
Your first code finds the value an element with a name of "body" inside e.target. I am assuming e is an Event, but there is no way to tell with the current amount of code you gave.
The second code just gets the value of the first INPUT element it finds.

jQuery chained functions and "this": Where is my syntax incorrect in this example?

Here's the situation:
I have 3 buttons
<button type="button" class="job-update-button wp-core-ui button-primary" id="delete-btn">Remove</button>
<button type="button" class="job-update-button wp-core-ui button-primary" id="update-btn">Update</button>
<button type="button" class="job-update-button wp-core-ui button-primary" id="add-btn">Add</button>
and an input
<input type="hidden" name="jobAction" value="" />
whose value is supposed to relate to the id of whichever button has been clicked. It might look silly, but this is my way of consolidating the logic on the page so that a single script on the server can handle a bundle of related AJAX requests.
delete-btn clicked --> jobAction gets value of delete
update-btn clicked --> jobAction gets value of update
add-btn clicked --> jobAction gets value of add
The function I'm using for the click events starts with
jQuery('.job-update-button').click(function(){
// change the value of the memberAction hidden input based on which member-update-button was clicked
jQuery('input[name="jobAction]"').val(jQuery(this).attr('id').substring(0, this.IndexOf('-')));
and I'm trying to figure out why I'm getting
this.IndexOf is not a function.
My thinking is that by the time I call this.IndexOf('-') the this refers to the object invoking substring, which is the string returned by jQuery(this).attr('id').
Is that wrong? If so, can you help me understand why? And is there a more efficient and compact way of going about this whole procedure?
Your Jquery function is messed up all you need is:
$('.job-update-button').click(function(){
// change the value of the memberAction hidden input based on which member-update-button was clicked
var id = $(this).attr('id');
var value = id.replace("-", " ");
$('input[name="jobAction"]').val(value);
})
For starters you dont need to call jQuery the shorthand way is simply $
It looks like you have a " outta place in your code. Change this:
'input[name="jobAction]"'
To:
'input[name="jobAction"]'
Working codepen example
Please note instead of:
jQuery('.job-update-button').click(function(){}
I used:
$('.job-update-button').click(function(){}
You could call jQuery every time but $ is easier.
If its not what you're looking for just let me know and I will edit or delete.
Let's break your code down a bit to make it clearer:
jQuery('.job-update-button').click( function(){
var value = jQuery(this).attr('id').substring(0, this.IndexOf('-'));
jQuery('input[name="jobAction"]').val( value );
});
Inside the click event handler, this refers to the HTML element that triggered it. That is just the way jQuery works internally (you can explicitly set this or 'scope' when calling or applying a function).
That means you are trying to call indexOf (note the correct spelling) on an HTML element, which does not have an indexOf method.
Also, note that most people use the $ shorthand for the jQuery method.
To fix your code, this would probably suffice:
$('.job-update-button').click( function(){
$('input[name="jobAction"]').val( $(this).attr('id').replace(/-btn$/, '') );
});
Here, I'm using the replace method with a Regular Expression in order to strip out the appended '-btn' part of the id.

Getting my javascript output to display in my HTML

I am sure this is a simple question.
To begin really playing with javascript and understand it I need to have the environment to see what my output is. I have done lessons in javascript but need to actually get the HTML and javascript talking.
What I am looking to do:
Have a user input information into an text box and have it show the result in the html.
is the sky blue? Yes (makes true be displayed on my HTML)
is the sky blue? No (makes false be displayed in my HTML)
currently i have no idea if my javascript is doing anything!
Here is my code:
HTML:
<form action="" onsubmit="return checkscript()">
<input type="text" name="value">
<input type="submit" value="Submit">
Javascript:
function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}
document.write(box);
I am so confused but need to see the results of what i am doing to see where to fix things, i tried using console in chromes inspect elements function but this has confused me more.
Can someone help and clean the code up to make sense by labelling everything as what they do?
box? check script?
Thanks :)
I updated the jsfiddle I had made for you. It's a working version that might get you started.
HTML
<!-- I avoided all the mess of forms, since that submits to a server, and that's more than you want right now. Note that I added ids to each input. Ids make it very easy to access the elements later. -->
<input type="text" name="value" id="fillIn">
<input type="button" value="Submit" id="button">
JS
// My methodology here is totally different, since I directly get the element I care about
function checkscript() {
// find the element in the DOM
var box = document.getElementById("fillIn");
// check for a value
if (box.value) {
// if there is one, add a new div. That's probably not what you'll want in the long run, but it gives you something to work with (and seems to match your old idea of using document.write. I have never yet used document.write, though others with more experience than I may like the concept better.
// This creates a new element. If you press F12 and look at this in your debugger, you'll see it actually appear in the HTML once it's appended
var newElement = document.createElement("div");
// Set the value to what you want
newElement.innerHTML = box.value;
document.body.appendChild(newElement);
} else {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
// No returns necessary, since we're not dealing with formsubmittal.
}
}
// This hooks up the function we just wrote to the click event of the button.
document.getElementById("button").onclick = checkscript;
This may or may not be what you want, but it's at least a place to get started.
A few things to start out:
1.) Make sure all elements have end tags
<input type="text" name="value" />
Note backslash at end of tag.
2.) You are using a form tag, which submits a form to a server side component.
Suggest you need to use the onclick event. Which is available on all input controls. Suggest you start with buttons so:
<input type="text" name="value" onclick="myFunction()" />
<script type="text/javascript">
function myFunction() {
document.write("Hello");
console.log("Hello");
}
</script>
Writes stuff directly to the html and console. Hope that gets you started.
Regards,
Andy

create a pop-up window and display a list of radio buttons using javascript

I'm writing on a js file.
Here is what I've tried so far. (My code is a bit long but here is what I'm trying to do)
var popUpList= $ ('<input type="radio">A<br> <input type="radio">B<br> <input type="radio">C');
var showPopUpButton=$('<button type="button">Select a Letter</button>');
// showPopUpButton is appended to the body
showPopUpButton.click(function() {
alert(popUpList);
});
When I click on showPopUpButton, the alert window shows [object Object], which I guess means that the variable popUpList is empty.
I couldn't find how to do that in javascript.
I also tried with jQuery as suggested here Create a popup with radio box using js
var popUpList= $ ('<input type="radio">A<br> <input type="radio">B<br> <input type="radio">C ');
showPopUpButton.click(function() {
popUpList.dialog();
});
Now, the buttons are displayed but not inside a pop-up window! And they are all superposed.
Any help will be appreciated.
Thanks!
You need to wrap your <input>s in a container element, e.g.: <div>, because dialog() works on a single element.
In your code, you are asking the dialog() function to work on multiple DOM objects and thus it will fail.
Here is the code:
var popUpList = $('<div><input type="radio">A<br><input type="radio">B<br><input type="radio">C</div>');
showPopUpButton.click(function() {
popUpList.dialog();
});
See it in action here. Try it yourself. :)
Changed your inputs to HTML string, parsing as HTML and inserting inside the #dialog element.
var popUpList= '<input type="radio">A<br> <input type="radio">B<br> <input type="radio">C',
dialogHtml = $.parseHTML(popUpList);
showPopUpButton.click(function() {
$( "#dialog" ).html(dialogHtml).dialog();
});

Setting the value of a hidden input

The idea: I'm setting the value of an input with type="hidden" via regular Javascript or jQuery.
The issue: neither jQuery nor document.getElementById will find the hidden input, even though I'm absolutely sure the selector is correct and there are no conflicting elements.
The code:
I can't really post much of it, because it's full of rather complicated PHP that confuses me when I just look at it.
Here's the javascript:
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
Note: there's nothing wrong with the selector, and the "input" is a different element that I'm using to reference the hidden.
Here's the HTML:
<input type="hidden" name="s<?=$step_counter?>_budget_hidden"
id="s<?=$step_counter?>_budget_hidden" value="0" />
The code is kind of out of context, but it's more of a general problem with Javascript than a syntactical error. Thoughts?
In $("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total); you take two chars before the first underscore in your hidden id. However your hidden id have only one char 's'
EDIT
Ok the <?= ?> was hidden before the question edit.
Do you call your script after the body onload event?
EX:
$(document).ready(function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").bind("keyPressed",function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
}
});
FYI: We can get the hidden input value using jQuery, even we can also edit any hidden input value using jQuery.
I think your way of getting the hidden value using 'substr' method is causing some problem. You are using like substr(0, 2) so are sure that the variable $step_variable is a single digit number, otherwise your code will not return correct result.
I am giving some sample code below, check it once.
Here's the javascript:
var input_id = $("hidden_val").attr("id").substr(1);
$("#" + input_id + "_budget_hidden").val(budg_total);
Here's the HTML:
input type="hidden" class="hidden_val" name="s_budget_hidden" id="s" value="0"
I think this will help you. Let me know if you are not following this flow to solve your issue.
I think that input.id.substr(0,2) says to start at the start of the string, take 2 characters and use that.
http://www.w3schools.com/jsref/jsref_substr.asp
Try using Firebug to see what the result of that method call is.

Categories