jquery post and redirect onclick - javascript

I have this html code
<div>
<div><input id="wpsl-search-input1"/></div>
<div><a id="wpsl-search-button1" href="#" target="_self">submit</a></div>
</div>
And this jquery
<script>
$('#wpsl-search-button1').click(function() {
var url = '/pages/location-search/?';
$('#wpsl-search-input1').each(function() {
url += 'zip=' + $(this).val() + "&";
});
window.location.replace(url);
});
</script>
But for some reason it doesn't work. Any help ?

Let me try to explain to you what you did and what you need to do to make your code work in the way you intended.
<script>
$('#wpsl-search-button1') // jQuery method to retrieve an element with the ID "wpsl-search-button1"
.click(function() { // Attach a "click" listener to the element
var url = '/pages/location-search/?'; // Declare a variable with the name "url" containing a string "/pages/location-search/?"
$('#wpsl-search-input1') // retrieving the element with the id "wpsl-search-input1"
.each(function() { // looping over all elements found by the id selector (ID's are unique, so the query above should always return one jQuery element. No need for a loop here)
url += 'zip=' + $(this).val() + "&"; // append a "zip" parameter with the value of the found element (this is refering to the current element of the iteration -> the input)
});
window.location.replace(url); // replace the current resource with the one in the "url" variable
});
</script>
If you just want to redirect to a url based by the input value use this code:
<script>
$('#wpsl-search-button1').click(function() { // you dont need the .each, because you are selecting by id
var inputURL = $('#wpsl-search-input1').val();
window.location.href = `/pages/location-search/?zip=${inputURL}`; // Redirecting to the passed url (also working relative to the current URL)
return false; // Cheap way to call the "event.preventDefault()" method
});
</script>

Try executing it after the DOM has loaded, like this:
<script>
$(function() {
$('#wpsl-search-button1').click(function() {
var url = '/pages/location-search/?';
$('wpsl-search-input1').each(function() {
url += 'zip=' + $(this).val() + "&";
});
window.location.replace(url);
});
});
</script>

When selecting an element by id, you need a pound sign:
$('#wpsl-search-input1')

Related

Splitting an href and putting the html into a variable

I want to send this HTML, minus "/modal" into a variable:
<span class="detailsLink"><object>DETAILS</object></span>
How can I add to this line to make it work?:
var eemailDetails = $('.detailsLink').html();
This ends up taking out /modal before it passes it into the variable:
var eemailDetails = $('.detailsLink a').each(function(){
this.href = this.href.replace('/modal', '');
}).html();
Thank you for your time!
The replacement should be made on the value retrieved instead of on the element's attribute.
So to retrieve the HTML markup including the targeted element, the outerHTML property can be used.
// Get the whole HTML
var eemailDetails = $('.detailsLink')[0].outerHTML;
// Remove /modal
eemailDetails = eemailDetails.replace('/modal', '');
console.log("The attribute unchanged: "+$('.detailsLink a').attr("href"));
console.log("The HTML retrieved: "+eemailDetails);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object>DETAILS</object></span>
So the each works fine, and I save the variable as a data-attribute on the element itself. Later, when it gets clicked, I can recall that data attribute as needed. Hope this helps!
$('.detailsLink a').each(function(){
var changedLink = this.href.replace('/modal', '');
$(this).data("changedLink", changedLink)
});
$(".detailsLink a").on("click", function(event){
event.preventDefault();
var returnEl = $(this).parents(".detailsLink").clone();
returnEl.find("a").attr("href", $(this).data("changedLink") );
console.log(returnEl[0].outerHTML );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="detailsLink"><object>DETAILS</object></span>
<span class="detailsLink"><object>More DETAILS</object></span>
<span class="detailsLink"><object>Yet More DETAILS!</object></span>

how to use an es6 template inside of html a tag href

Hey everyone this is the first time asking a question on here. So here we go. I have a ajax request with json return. I'm trying to now take the response and dynamically create the recipe title but also create an a href with the response data.
$( window ).load( function() {
$.get({
url: window.location.href + ".json"
}).success( function( response ) {
console.log( response );
let $title = $( ".js-title" );
let reviewCount = 0;
while( reviewCount < $title.length ) {
let recipe_title = response[reviewCount].recipe.title;
let href = response[reviewCount].location.href;
$title[reviewCount].prepend( `<a>${ recipe_title }</a>` ).attr('href', `${ href }`);
reviewCount++;
}
});
});
I'm having trouble figuring out the href part of things.
Can add href in the template( while creating element ) and no need to use attr function.
example snippet to support above statement:
function prepend() {
let title = 'something';
let href = 'something/else'
$('div').append(`<a href='${href}'>${title}</a>`)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>
To User stand what is wrong with what you did:
No doubt jQuery prepend method is chainable but it will return the element that it applied upon. Therefore if you open inspector you should see href is getting added in $title[reviewCount] element.
To do this correct you need to construct the a element and then prepend it.
Example snippet.
function prepend() {
let title = 'something';
let href = 'something/else';
$('div').prepend($('<a></a>').text(`${title}`).attr('href', `${href}`))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>
To prepend in specific element:
We need to use eq method of Jquery, again this is cahinable.
Use:
$title.eq(reviewCount).prepend($('<a>').text(`${ response[reviewCount].recipe.title }`).attr('href', http: //localhost:3000/recipes/`${recipe_id}`));

Check if a class or id exist in html response from ajax call

I know we can use hasClass() but in my case my ajax is returning html.
I can append then check the class exist or not but there'll be a flick. Is it possible to check what's inside the html before render it somewhere?
$.ajax({
url:'some_url',
success: function(html) {
// I can do this:
$('body').append(html);
if ($('my_selector').length > 0) {
// but I don't want to do this because I don't want that the html will show to the user
}
}
});
Yes, Possible
var yourReturnedHtml = getHtml();
return $(yourReturnedHtml).find('.someClass').length > 0;
Further #Mohammad Adil answer:
var html = '<div class="test">This is the response from the ajax call.</div>';
function simulateAjax(selector) {
var exist = $('<div />').html(html).find(selector).length > 0;
$('#result').append('The element "' + selector + '" ' + (exist ? '' : 'not ') + 'exist<br />');
}
simulateAjax('.test');
simulateAjax('.test1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
The difference between the answers, and I think that the reason it didn't work for you, that for example: If your response is <div class="test"></div>, the #Mohammad's script will return false because there is no element with the class .test in the main element in the response.
So, you should wrap the response with element, then you can use .find() to check.
Sure working method, used many time into my projects, This will help you find any elements, elements with some class or id.
You can append your ajax response to some hidden html element e.g div
e.g.
<div id="responseDiv" style="display: none"></div>
//Now write a function to save ajax response to div
//from this div, you can find out whether class or any element is there
$.ajax({
url: 'some url',
success: function(data){
//save response to div
$('#responseDiv').html(data);
//now to check whether some class exists in the div
if($('#responseDiv .class-to-find').length > 0){
//since class is found into ajax response, write your code here
}
}
});
i got your point now. Use the same approach of hasClass() in success function of ajax and using async parameter. To remove the flick, place your ajax code is seTimeOut with time 0 like
setTimeout(function(){ //Your ajax code here }, 0);

How can I get access to value of a field in a HTML page inside other pages

My problem is that I want to take the value of a text field from one HTML page to another one.
According to the following code, at the first page, I can get the value of the sms_name text field by using onclick attribute. But I can not get access to that at the other page.
I used many solutions but no success until now.
HTML file #1:
<div style="width:100%;height:34%;;margin-top:20%" >
<div class="message-onclick" onclick="
var sms_name= document.getElementById('recepient-name').value;
alert(sms_name);
"> </div>
</div>
HTML file #2:
<div class="log-divs" style="height:7%;border:1px solid red" onclick="
alert(sms_name); ">
</div>
If your really want to do this using javascript only, you don't need any particular js library, just pass the value to your second page using a get parameter:
In your first file:
window.location.href = 'secondfile.html?sms_name=' + sms_name;
In your second file:
var param = 'sms_name';
// get the position of your parameter in the url
var paramIndex = window.location.href.indexOf(param + '=')
, value = window.location.href.substr(paramIndex + param.length);
// find where your value ends
var valueEndIndex = value.indexOf('&');
// if other params follow, take them off
if (valueEndIndex !== -1) value = value.substr(0, valueEndIndex);
// that should do it
alert(value);
You'll need to add the jQuery library to the header of the page sending. Then, just add the codes below to the headers of each page accordingly (on the page sending, after the jQuery library).
Page sending:
<script type="text/javascript">
var sms_name = $("#recepient-name").val();
$.ajax({
type: "GET",
url: "your-other-page.html",
data: {
sms_name: sms_name
}
});
</script>
Page receiving:
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
alert(urlParams["sms_name"]);
</script>
Based on this post: How can I get query string values in JavaScript?

Get attr(id) with a known href variable

I want to get the id name thanks to a href value that is set in a variable.
To do this, I want to:
get the attr('href') of a clicked element (that works).
put it in a variable (OK).
search this href in a every class called ".link" (not in #prev-ajax, #next-ajax id) (problem)
Get the parent id.
I tried this :
$('#prev-ajax,#next-ajax').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$(".link[href*= href ]:not('#prev-ajax,#next-ajax')");
var ajax = $(this).parents('.element').attr('id');
alert(ajax);
});
As you're using a JavaScript variable, you need to escape the quotes. Also, don't wrap items in the :not selector in quotes.
Try this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
Edit: Looking at your fiddle, you're also not doing anything with that selector. See this:
$(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = $(this).parents('.element').attr('id');
It should be:
var link = $(".link[href*= '" + href + "']:not(#prev-ajax, #next-ajax)");
var ajax = link.parents('.element').attr('id');
Demo: http://fiddle.jshell.net/UKyT4/1/

Categories

Resources