JS code to change form submit is not working - javascript

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

Related

jQuery getJSON and get value from button

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.

JQuery string printout disappears

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>");
});
});

Replacing input with div, after replacing div with input

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)

Javascript Parameter Passing Not Working

The code dynamically creates a listview which works but i want to make it so when a listview item is clicked it sends the a url paramater to another method. When i set a paramater it doesnt alert the paramater, but when i give no parameter it works.
var output =
"<li onclick='openURL()'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
The above works - No parameter in openURL();
var output =
"<li onclick='openURL('" + results.rows.item(i).url + "')'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";
The above doesnt work - I have done alert(results.rows.item(i).url) and it has a value.
function openURL(url) {
alert("opening url " + url);
}
Could someone explain what i'm doing wrong, i've been trying to solve the problem for hours.
Cheers!
You are using single quotes to open the HTML attribute, you can't use it as JavaScript String because you'll be closing the HTML attribute, use double quotes:
var output =
"<li onclick='openURL(\"" + results.rows.item(i).url + "\")'><h3> Module Code: " +
results.rows.item(i).module
+ "</h3>Room: "
+ results.rows.item(i).room +
"</li>";

Div's content editor

I have this code:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#k123").click(function () {
//var text=$(this).val(); //this does not work
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" onclick="save();" value="save"><input type="button" onclick="cancel();" value="cancel"></div>';
$(this).replaceWith(k);
});
});
function save() {
}
function cancel() {
//alert(text);
var k='<div id="k123"></div>';
$("#k123").replaceWith(k);
}
</script>
</head>
<body>
<div id="k123">aaaaa</div>
</body>
</html>
My question is :
1)In both functions : cancel & save , How can I get content of div id->#k123->textarea->content
functions cancel & save are outside the scope and they are independent functions I cannot tell $(this).parent().
I need to ask about div which has id #k123 , then get inside to textarea's content and get it.
and I have also to get id #k123 automatically because if I have many divs I cannot tell save & cancel manually the div's id, cancel & save should know the div's id sender from the input type='button'`s parent id.
**please I do not prefer the suggestion of sending div id from input button
**We are assuming that both input buttons have no IDS or Names
I tried another way but still having same problem
I replaced
$(document).ready(function() {
$("#k123").click(function () {
var text=$(this).text();
var k='<div id="k123"><textarea rows="10" cols="10">' + text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel"></div>';
$(this).replaceWith(k);
});
//$("#k123 > input").click(function() {
$("#k123").children("input:second").click(function() {
alert("hi");
});
});
thank you.
I have the working code for you below. You don't even need an id.. just a container div and delegation of events. The below accomplishes what I thought you were after, in what I believe to be a much simpler, and much more efficient fashion:
(I've added comments to assist in understanding the code)
$(document).ready(function() {
$(".container").on('click', function(e) {
if (!$(e.target).is('input') && !$(e.target).is('textarea')) { //check to make sure the target is neither an input or a textarea
var div_text = $(e.target).text(); // use a variable named something other than text, because text is already a method for another element
$(e.target).data('text',div_text); // set the div's current contents as a hidden data attribute, to be retrieved later. You can get rid of this and the other line if you want cancel to completely wipe the div.
var k = '<textarea rows="10" cols="10">' + div_text + '</textarea><br /><input type="button" value="save"><input type="button" value="cancel">';
$(e.target).html(k); //set the inner HTML of the div, so we don't lose any data saved to that div
}
if ($(e.target).is('input') && $(e.target).val() == 'save') {
$(e.target).parent().html($(e.target).parent().find('textarea').val()); // replace the current contents of the parent div with the contents of the textarea within it.
} else if ($(e.target).is('input') && $(e.target).val() == 'cancel') {
$(e.target).parent().html($(e.target).parent().data('text')); //set the contents to the old contents, as stored in the data attribute. Just replace the contents of the .html() here with '' to completely clear it.
}
});
});​
DEMO
REVISED - WORKS
Check this out... not quite there but close!
REVISED JS Fiddle
function editit() {
var divId = $(this).attr('id');
var text = $(this).html();
var k = '<div id="' + divId + '" class="editable"><textarea id="newvalue' + divId +'" rows="10" cols="10">' + text + '</textarea><br /><input id="save' + divId + '" type="button" value="save"><input id="cancel' + divId + '" type="button" value="cancel"></div>';
$('#' + divId).replaceWith(k);
$('#cancel' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + text + '</div>');
$('.editable').bind('click', editit);
});
$('#save' + divId).click(function() {
$('#' + divId).replaceWith('<div id="' + divId + '" class="editable">' + $("#newvalue" + divId).val()+ '</div>');
$('.editable').bind('click', editit);
});
}
$('.editable').bind('click', editit);

Categories