I replace a div with a text input so the user can edit the text. When the user hits enter, I want the text input to change back into a div with the edited text.
The problem I'm having I can't get the text input to change back into a div after pressing enter. I've tried replaceWith() and a number of combinations of JQuery functions that should do this, but I can't figure it out. Can anyone help?
Here is the div containing the comment text to be edited
<div id="comment-message-' + comment.id + '">' + comment_message + '</div>
The user clicks a link to edit the comment and the comment turns into a text input. This works fine
Edit Comment
This is the function that changes the comment into a text input. This works
function editComment(id) {
var t = $('#comment-message-' + id).text();
$('#comment-message-' + id).replaceWith('<form id="edit-comment-form-' + id + '" name="edit-comment-form-' + id + '" action="javascript:callAPI(' + id + ')"><input id="edit-comment-' + id + '" name="edit-comment-' + id + '" type="text" value="' + t + '"/></form>');
}
Using the Facebook API, I make the call. If there is no error, the text input changes into a div with the new comment. The API call here works, but the change from text input to div does not
function callAPI(id) {
var e = document.getElementById('edit-comment-' + id).value,
edit = { message: e };
FB.api('/' + id, 'POST', edit, function (response) {
if (response && !response.error) {
var comment = $('#comment-message-' + id),
form = $('#edit-comment-form-' + id); // forgot to add '#' here
comment.removeChild(form);
comment.html('<div id="comment-message-' + id + '">' + e + '</div>');
}
});
}
use below code to replace input type to div
FB.api('/' + id, 'POST', edit, function (response) {
if (response && !response.error) {
$('#edit-comment-form-' + id).replaceWith('<div id="comment-message-' + id + '">' + e + '</div>')
}
});
you alrady replace $('#comment-message-' + id) with input form so do same you need to replace $('#edit-comment-form-' + id) to $('#comment-message-' + id)
Related
I'm download data from JSON file and display button with value:
function iterateOverPrzepisy(best) {
$('#listaPrzepisow').html('');
$.getJSON('przepisy.json', function(data) {
for (var x in przepisyDost) {
$('#listaPrzepisow').append(" <div data-role=\"collapsible\"><h2>" + przepisyDost[x].nazwa + "</h2>" +
"<ul data-role=\"listview\" data-theme=\"d\" data-divider-theme=\"d\">" +
"<li>" +
"<h3>Składniki: " + przepisyDost[x].skladniki + "</h3>" +
"<p class='ui-li-desc' style='white-space: pre-wrap; text-align: justify;'>" + przepisyDost[x].tresc + "</p>" +
"<button id='ulubioneBtn' value='" + przepisyDost[x].id + "'>Ulubione</button></li>" +
"</ul>" +
"</div>");
j++;
}
})
}
When I click to button #ulubioneBtn I would like to get value from this button. So I add done to getJSON
}).done(function(data){
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $("button#ulubioneBtn").val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
});
But it's not working. When I click on button Ulubione I always get in console log value = 0
The problem seems to be that you add multiple buttons with the same id. An id of a html element should be unique.
przepisyDost does not appear to be defined at
for (var x in przepisyDost) {
? Try
for (var x in data.przepisyDost) {
Duplicate id's are appended to document at
"<button id='ulubioneBtn' value='" + przepisyDost[x].id
+ "'>Ulubione</button></li>" +
within for loop. Try substituting class for id when appending html string to document
"<button class='ulubioneBtn' value='" + data.przepisyDost[x].id
+ "'>Ulubione</button></li>" +
You could use event delegation to attach click event to .ulubioneBtn elements, outside of .done()
$("#listaPrzepisow").on("click", ".ulubioneBtn", function() {
// do stuff
})
I have created a dummy JSON and executed the same JS with a single change.
In onclick handler instead of getting button I am using $(event.target).
And it is working fine.
Please find the fiddle https://jsfiddle.net/85sctcn9/
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $(event.target).val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
Seems like first object doesn't have any id value.
Please check JSON response returned from server.
Hope this helps you in solving.
I'm trying to add text in a textarea. I think I'm missing some ....my code is below:
$.each(result, function (i, v) {
if (ui.item.value === v.TextKeyword) {
if ($('input:radio[name="' + currentid + '"]:checked').val() == 'Append') {
var cannedtext = $("textarea[parentcontrolid='" + currentid + "']").text() + "," + v.Text;
$("textarea[parentcontrolid='" + currentid + "']").text(String(cannedtext));
} else {
$("textarea[parentcontrolid='" + currentid + "']").text(v.Text);
}
$("textarea[parentcontrolid='" + currentid + "']").focus();
}
});
but when I execute the code it displays this:
You have to use .val() instead of .text().
According to Jquery:
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method. To get the value of a script element, use the .html() method.
I have an Ajax call that returns an array of movie titles. I'd like to click on a button next to each title and add the title to a "currently watching" list. My "add" link doesn't seem to be accepting the event handler. What can I do to add the specified title to my "currently watching" list
$("#search").click(function(event){ event.preventDefault();
var show = $("#showTitle").val().toLowerCase();
console.log("the show title is " + show);
var url = "https://api.themoviedb.org/3/search/movie?query=" + encodeURIComponent(show)+ "&api_key=9b97ec8f92587c3e9a6a21e280bceba5";
console.log(url);
$.ajax ({
url: url,
dataType: "json",
success: function (data) {
// console.log(data.results);
var htmlStr = '';
$.each(data.results, function(i, results){
htmlStr += '' + 'Add' + ' <h2 class="movie-title">' + results.original_title + '</h2>' + "Average Rating " + results.vote_average + '<br>' + '<p class="showDescription">' + results.overview + '</p>' + '<br />' + '<img src=https://image.tmdb.org/t/p/w185' + results.poster_path + '>';
});
// console.log(htmlStr);
$('#searchresults').html(htmlStr);
}
// updateCount(); - count the classes inside the "currentywatching" function
}); //close .ajax
});
$('.addCurrentlyWatching').on('click', function(e){
e.preventDefault();
var movieTitle = $('.movie-title').text();
// console.log(movieTitle);
$('.currently-watching').append('<li>' + movieTitle + '</li>');
});
<section id = "shelf1">
<h2> Currently Watching </h2>
<ul class="currently-watching"></ul>
<div class="number">
<p> You currently have <span id="count"> 0 </span> shows in this list. </p>
</div>
</section>
The solution:
$(document).on('click','.addCurrentlyWatching', function(e){
e.preventDefault();
var movieTitle = $('.movie-title').text();
// console.log(movieTitle);
$('.currently-watching').append('<li>' + movieTitle + '</li>');
});
If you are interested in a more detailed answer:
Explanation
use
$('body').on('click','.addCurrentlyWatching', function(e){
take a look at Event binding on dynamically created elements?
and in
' + 'Add' + '
if you have Add variable defined use
' + Add + '
if you not
Add
and you can use
var movieTitle = $(this).next('.movie-title').text();
instead of
var movieTitle = $('.movie-title').text();
For older versions of jQuery use $.live & $.delegate
Docs:
http://api.jquery.com/live/
http://api.jquery.com/delegate/
I am new to JQuery.
Trying to create a blog page. When user enters name, country and comment, i want to print it out underneath the HTML form.
The script i'm using is as follows:
<script>
$(document).ready(function() {
$(".addButton").click(function() {
var name = $("input[name=name]").val();
var country = $("select[name=countries]").val();
var comment = $("textarea[name=comment]").val();
$(".comments").append("<div class='new-comment'>" + name + " (" + country + "):</br>" + comment + "</div>");
});
});
This prints out my variables but only for a fracture of a second and they disappear. Any explanation would be highly appreciated.
Thank you.
<button> tags will submit the form, causing the page to reload. Use Event.preventDefault() to stop the form submission.
$(document).ready(function() {
$(".addButton").click(function(e) {
e.preventDefault();
var name = $("input[name=name]").val();
var country = $("select[name=countries]").val();
var comment = $("textarea[name=comment]").val();
$(".comments").append("<div class='new-comment'>" + name + " (" + country + "):</br>" + comment + "</div>");
});
});
I have a form that has many fields in it. I am using JS code to modify the parameters submitted by that form via GET request.
Basically the form submits 3 params- search_address, search_city,search_state, search_zip along with other params-- My JS code just combines the address, city, state, and zip params into a single param and modifies the search query accordingly.
But when I run the page with the code below, the original query goes through as it is- as if the JS code has no effect. What am I doing wrong here?
This is the HTML code for the form HTML tag--
<form method="get" class="searchform" id="searchform" action="target_URL_value">
This is the HTML code for the submit button--
<input type="submit" class="submit" name="submit" id="searchsubmit" onclick="JavaScript:submit_form()" style="width:20%" />
This is the Javascript code for submit_form function--
<script>
function submit_form()
{
$('searchform').submit( function() {
var $form = $(this);
//Arvind IMP put the below paraemeter's name as s or the value of name in Search field of original header.php in parent template...
// This is a typical search string
//?post_type=property&search_keyword=&submit=Search&price-min=&price-max=&city=&state=&zip=&beds=&baths=&sqft=&status=
var data = 'post_type='+$('#post_type').val()+'&search_keyword='+$('#search_address').val()+", "+$('#search_city').val()+", "+$('#search_state').val()+", "+$('#search_zip').val()
+ '&price-min='+$('#price-min').val()+ '&price-max='+$('#price-max').val() +'&city='+$('#search_city').val()
+ '&state='+$('#search_state').val()+ '&zip='+$('#search_zip').val() +'&beds='+$('#beds').val()
+ '&sqft='+$('#sqft').val()+ '&status='+$('#status').val();
$.get( $form.attr('action'), data);
return false;
});
}
</script>
Do not declare the submit event into a function.
Also remove inline code onclick="JavaScript:submit_form()"
And finally, do not forget the # of the form selector $('#searchform') to select the id (or . to select the class)
$(document).ready(function () {
$('#searchform').submit(function () {
var $form = $(this);
//Arvind IMP put the below paraemeter's name as s or the value of name in Search field of original header.php in parent template...
// This is a typical search string
//?post_type=property&search_keyword=&submit=Search&price-min=&price-max=&city=&state=&zip=&beds=&baths=&sqft=&status=
var data = 'post_type=' + $('#post_type').val() + '&search_keyword=' + $('#search_address').val() + ", " + $('#search_city').val() + ", " + $('#search_state').val() + ", " + $('#search_zip').val() + '&price-min=' + $('#price-min').val() + '&price-max=' + $('#price-max').val() + '&city=' + $('#search_city').val() + '&state=' + $('#search_state').val() + '&zip=' + $('#search_zip').val() + '&beds=' + $('#beds').val() + '&sqft=' + $('#sqft').val() + '&status=' + $('#status').val();
$.get($form.attr('action'), data);
return false;
});
});
Your selector is incorrect. Plus you are registering the handler again and again, calling the submit button click. You dont need it. Just place your handler under document.ready to register first up.
Script
<script>
$(function(){
$('.searchform').submit(function () {
var $form = $(this);
//Arvind IMP put the below paraemeter's name as s or the value of name in Search field of original header.php in parent template...
// This is a typical search string
//?post_type=property&search_keyword=&submit=Search&price-min=&price-max=&city=&state=&zip=&beds=&baths=&sqft=&status=
var data = 'post_type=' + $('#post_type').val() + '&search_keyword=' + $('#search_address').val() + ", " + $('#search_city').val() + ", " + $('#search_state').val() + ", " + $('#search_zip').val() + '&price-min=' + $('#price-min').val() + '&price-max=' + $('#price-max').val() + '&city=' + $('#search_city').val() + '&state=' + $('#search_state').val() + '&zip=' + $('#search_zip').val() + '&beds=' + $('#beds').val() + '&sqft=' + $('#sqft').val() + '&status=' + $('#status').val();
$.get($form.attr('action'), data);
return false;
});
});
</script>
Remove onclick="JavaScript:submit_form()" from your button as you don't need it.
<input type="submit" class="submit" name="submit" id="searchsubmit" style="width:20%" />
Demo
You forgot a dot to designate the class, see:
$('searchform').submit( function() {
^----- HERE you lack a dot . to select class name
You need use preventDefault():
function submit_form()
{
$('.searchform').submit( function(e) {
e.preventDefault();
//rest of code
});
}
second add dot to selector .searchform;
third remove onclick="JavaScript:submit_form()" from your form