JQuery string printout disappears - javascript

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

Related

How to click each link individually in JS?

Try to separate both links individually by clicking each of them. What should I edit or add?
<script type="text/javascript">
$('#submit').click(function() {
if ($('#user').val() != '') {
alert('For demonstration purposes only. Please do not point your RSS reader to this server.');
var user = $('#user').val();
First One
$('#output')
.html('')
.append('hhtp://www.breakingnews.com/feeds/rss/' +
$('#user').val())
.attr('href', 'http://www.breakingnews.com/feeds/rss/' +
$('#user').val());
Second One
$('#output')
.html('')
.append('https://www.theguardian.com/world/' + user +
'/rss')
.attr('href', 'https://www.theguardian.com/world/' + user + '/rss');
var user = $('#user').val();
$('#output')
.html("")
.append(jQuery('<a>').attr('href', 'hhtp://www.breakingnews.com/feeds/rss/' +
user).text('hhtp://www.breakingnews.com/feeds/rss/' + user));
$('#output')
.append('<br/>')
.append(jQuery('<a>').attr('href', 'https://www.theguardian.com/world/' + user + '/rss').text('https://www.theguardian.com/world/' + user + '/rss'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" value="user"></input>
<div id="output"></div>
Problem is in
.html('')
when you add new link you erase all html content added before.
You should to remove this method in second link creation code.
And you should create a link element
Create a link, you are adding a attributes to a text
var user = "user";
$('#output').empty().append('https://www.theguardian.com/feeds/rss/' + user + '/rss').append('<hr>https://www.theguardian.com/world/' + user + '/rss');

hyperlink alternate text replacement

At the moment i've got this code, which replaces a span class whith a hyperlink. The hyperlink includes a abbreviation and the alternate texxt for the hyperlink includes the same abbreviation. Now what i want to do is, to somehow replace the second abbreviation in the alternate text of the hyperlink. So that there isn't "click here to visit + 'name of'abbreviation" but instead an alias. So if the abbreviaton is ggl, the alias should be google. But the hyperlink shouldn't use this alias. Can sb help me? thx
(function($) {
var number = "1234567";
function linkBuilder(abbreviation) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation + "</a>";
}
function linkBuilder2(abbreviation2) {
return "<a href='https://www.test.com/" + abbreviation2 + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation2 + "</a>";
}
jQuery(document).ready(function() {
var fl = $(".first-link");
if (fl.length > 0) {
fl.html(linkBuilder(fl.data("abbreviation")));
}
var sl = $(".second-link");
if (sl.length > 0) {
sl.html(linkBuilder2(sl.data("abbreviation2")));
}
});
})(jQuery);
Here is a working jsfiddle:
https://jsfiddle.net/e7qdx031/1/
linkBuilder() should be re-usable, as kalsowerus mentioned.
Another thing that should be mentioned is that the following code returns a collection of elements, not just a single element.
var fl = $(".first-link");
...
var sl = $(".second-link");
The code you have provided will not function properly if there are multiple .first-link classes on the page. So instead I would iterate over each element using $.each() and run the linkBuilder() function on them individually.
As for the linkBuilder function I would modify it to accept the element object, then read the properties to retrieve alias and name. Full name is something that you seemed to indicate you need, but was not present in the code.
(function($) {
var number = "123456";
function linkBuilder($obj) {
var abbreviation = $obj.data('abbreviation');
var name = $obj.data('name');
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + name + "</a>";
}
jQuery(document).ready(function() {
$('.first-link, .second-link').each(function(index, obj){
$(obj).html(linkBuilder($(obj)));
});
});
})(jQuery);
What you probably want is something like this:
function linkBuilder(abbreviation, alias) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + alias + "</a>";
}
Just pass the display-name you want for your link as the second argument.

Passing a value from html to javascript function on click?

Basically, on clicking any image on a html page I want the id associated to be passed to a function.
This is what I have tried. It seems I am making a minor mistake here as I am getting the first id passed no matter what image I click from the array. I tried $(this).attr("id") as well, but did not work.
for(var i=0;i<jsonObj.length-1;i++){
var rows = '';
var bg_img = jsonObj[i].img;
var bg_img = decodeURIComponent(bg_img);
rows = "<img id='" + jsonObj[i].source_id + "' src='" + bg_img + "'/>";
document.getElementsByClassName('subscription')[i].innerHTML = rows;
}
$("body").delegate(".subscription", "click", function() {
// var id = $(this).attr("id");
alert("Welcome Test " + $('img').attr("id"));
return false;
});
$("img").click(function()
{
var id = $(this).attr("id");
});
Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page.
Try $('img',this) instead.

JS code to change form submit is not working

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

Display form input in same page

I am working on a simple form demo and i would like the input to display in a below the form. Currently i have it populating in the console. How do i may it display in the div when i click the submit button?
My code:
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$('#firstName').val();
$('#lastName').val();
$('#phoneNumber').val();
$('#address').val();
console.log($('#firstName').val());
console.log($('#lastName').val());
console.log($('#phoneNumber').val());
console.log($('#address').val());
});
});
Well, you're currently not putting the values anywhere but into the console.log.
I would expect to see something like (let's call your div you want the values to go to, "output"):
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
// Borrowing from another response, this is better
// Putting these in variables protects you from
// 1) accidentally modifying your form values
// 2) invalid input, if you add some basic checks, like
// testing to see if the length is > 0, doesn't contain
// bad characters, etc.
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
phone = $('#phoneNumber').val(),
address = $('#address').val();
// get a reference to the div you want to populate
var $out = $("#output");
// This is a better way of dealing with this
// because every call to .append() forces DOM
// reparsing, and if you do this too often, it can cause
// browser slowness. Better to put together one string
// and add it all at once.
$out.html("<p>" + firstName + "</p>" +
"<p>" + $('#lastName').val() + "</p>" +
"<p>" + $('#phoneNumber').val() + "</p>" +
"<p>" + $('#address').val() + "</p>");
});
});
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
$(this).after('<div>First name: '+$('#firstName').val()+'<br>'+
'Last name: '+$('#lastName').val()+
' .... ');
});
});
First of all, the four lines where you read the .val() but don't do anything with it are essentially wasted cycles, you probably meant to store them in variables:
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phoneNumber = $('#phoneNumber').val();
var address = $('#address').val();
To show them in some other element, use the setter version of .val() for input types, or .text() if it's a display type (div, span, etc):
$('#someOtherElement').text(firstName + '\n' +
lastName + '\n'
phoneNumber + '\n'
address);
$(document).ready(function() {
$('.submitForm').on('click',function(event){
event.preventDefault();
//$('#firstName').val();
//$('#lastName').val();
//$('#phoneNumber').val();
//$('#address').val();
var htmlContent = $('#firstName').val() + '<br />' + $('#lastName').val() + '<br />' + $('#phoneNumber').val() + '<br />' + $('#address').val();
$('#ID_OF_YOUR_DIV_HERE').html(htmlContent);
});
});
Maybe this is what you're after??
You can add it to a div you want with .append(), for example
$("#divYouWantToAddTo").append($('#firstName'));
I don't know where to start... What is all that $('#....').val() in the middle there, wasting time only to throw away the result..?
What is wrong with document.getElementById('...').value instead of wasting time creating an entire jQuery object just to access something trivial?
Adding text to a node is as simple as container.appendChild(document.createTextNode(sometext)); - and if you want to have newlines between them you can also do container.appendChild(document.createElement('br'));.
There is no need for jQuery here at all...

Categories