How do I convert this jQuery codes to JavaScript? - javascript

I am having trouble in solving my previous post. I only got a solution which requires jQuery, but I want to use JavaScript instead.
Really need help on this.
Previous Post (For Reference) : HTML - How To Display & Direct Selected Values From Drop Down Menu To A New HTML Page
This is the first jquery codes.
<input type="submit" id="btngo" value="Go" />
<script type="text/javascript">
$(function() {
$("#btngo").bind("click", function() {
var url = "Page2.htm?foodbeverage=" + encodeURIComponent($("#foodbeverage").val()) + "&status=" + encodeURIComponent($("#status").val());
window.location.href = url;
});
});
</script>
This is the second jquery codes.
< script type = "text/javascript" >
var queryString = new Array();
$(function() {
if (queryString["foodbeverage"] != null && queryString["status"] != null) {
var data = "<b>Food Beverages:</b> " + queryString["foodbeverage"] + " <b>Dine Takeaway:</b> " + queryString["status"];
$("#showdata").html(data);
}
}); <
/script>

I've converted the first snippet to a native JS equivalent. I didn't add the status to the URL, it is just more of the same as getting the food beverage.
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
// Get the input element from the DOM.
var beverage = document.getElementById('foodbeverage'),
// Get the value from the element.
beverageValue = beverage.value,
// Construct the URL.
url = 'Page2.html?foodbeverage=' + encodeURIComponent(beverageValue) + '&status=test';
// Instead of going to the URL, log it to the console.
console.log('goto to URL: ', url);
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
<label>
Beverage:
<input type="text" id="foodbeverage"/>
</label>
<input type="submit" id ="btngo" value="Go" />

For the second code snippet, add a div to the form/page. The JS function below will update the div value on window onload with parameters passed. Note that div is only updated if both the querystring paramaters are present.
<div id="showdata"></div>
<script type="text/javascript">
window.onload = passParameters;
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
var foodbeverage = getParameterByName("foodbeverage");
var status = getParameterByName("status");
if (foodbeverage != null && status != null) {
var data = "<b>Food Beverages:</b> " + foodbeverage + " <b>Dine Takeaway:</b> " + status;
document.getElementById("showdata").innerHTML = data;
}
}
//Get URL parameter value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

Related

php javascript onclick value change

I want to remove the "http" if it is put in the url part of the input link, before the data is sent.
this my input code look onclick=
<input style=" outline: none;" type="button" onclick="formatText ('link:url');" class="btn btn-yeni" value="link"/>
This my javascript code (the received data is sent to another file and replaced.)
<script type="text/javascript">
function formatText(tag) {
var Field = document.getElementById('entry_girdi');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value += '(' + tag + ')';
}
</script>
what i want to do If the input value is "link: http: //example.com" I would like to change it and post it as "link: example.com".
Can you try in your url string :
var result = url.replace(/(\w+:|^)\/\//, '');
result variable will hold "link : example.com" in place of "link : http://example.com"
Use the replace() function to replace part of a string.
function formatText(tag) {
var Field = document.getElementById('entry_girdi');
Field.value = Field.value.replace("http://", "");
Field.value += '(' + tag + ')';
}

Making use of a JSON attribute that doesn't always exist. Using jquery

I am writing a short script that connects to the LastFM api to get my last scrobbled song. The issue I am having is that the JSON version has an attribute for "now playing" which when you are currently listening to a song has the value of "true". However if there is no song playing the attribute doesn't exist at all.
This is the script I currently have and when I am listening to a song via spotify or iTunes etc... it works fine.
<p>
<p class="nowplaying"> <span class="track"></span> by <span class="artist"></span></p>
<p>
<script type="text/javascript">
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=JamesTaylor87&api_key=ADD-API-KEY-HERE&format=json', function(data) {
var artist = $(".artist"),
track = $(".track"),
np = $(".nowplaying"),
artistVal = data.recenttracks.track[0].artist["#text"],
trackVal = data.recenttracks.track[0].name,
nowplaying = data.recenttracks.track[0]["#attr"].nowplaying;
if(typeof nowplaying === "undefined"){
np.prepend("The last song I listened to was")
artist.append(artistVal);
track.append(trackVal);
} else {
np.prepend("I am currently listening to")
artist.append(artistVal);
track.append(trackVal);
}
});
</script>
However when I am not listening to anything I get the following error message (in safari) and nothing works:
undefined is not an object (evaluating 'data.recenttracks.track[0]["#attr"].nowplaying')
in chrome the error is displayed as follows:
Uncaught TypeError: Cannot read property 'nowplaying' of undefined
I have attempted to use an if statement for when it's undefined which hasn't worked and don't really know what else to try. Any help would be much appreciated.
Replace
data.recenttracks.track[0]["#attr"].nowplaying
with
data.recenttracks.track[0]["#attr"] && data.recenttracks.track[0 ["#attr"].nowplaying
That should stop the error occuring if data.recenttracks.track[0]["#attr"] is undefined
Try changing the line where you defined nowplaying to this:
nowplaying = (data.recenttracks.track[0]["#attr"]) ? data.recenttracks.track[0]["#attr"].nowplaying : undefined;
According to the chrome error, data.recenttracks.track[0]["#attr"] is undefined, which means you can't look for a property on it. You can use an if statement or a ternary to check whether this is defined before checking for its nowplaying property.
var attrs = data.recenttracks.track[0]["#attr"];
if (typeof attrs !== 'undefined') {
var nowPlaying = attrs.nowplaying;
}
Try this:
var track = data.recenttracks.track[0];
var nowplaying = track.hasOwnProperty('#attr') && track['#attr'].nowplaying;
I just built a very similar function for my site with Last.fm, and ran into this same problem. I was able to solve the problem by removing subsequent .nowplaying that you've included.
See below. Hope it's helpful!
// get the api
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOURUSERNAME&limit=1&api_key=YOURAPIKEY&format=json', function(data) {
var latesttrack = data.recenttracks.track[0]
var trackTitle = latesttrack.name
var trackArtist = latesttrack.artist["#text"]
// detect if the track has attributes associated with it
var nowplaying = latesttrack["#attr"]
// if nowplaying is underfined
if (typeof nowplaying === 'undefined') {
$('.nowplaying').html("Currently listening to nothing.")
} else {
$('.nowplaying p').html("Currently listening to" + trackTitle + " by " + trackArtist)
}
});
See it in action here: http://theadamparker.com/daily
<script type="text/javascript">
//<![CDATA[
var lastfm_api = 'http://ws.audioscrobbler.com/2.0/';
var lastfm_methods = 'user.getRecentTracks';
var lastfm_user = 'YOUR_USERNAME';
var lastfm_key = 'YOUR_APIKEY';
var lastfm_limit = '1';
var lastfm_json = lastfm_api + '?method=' + lastfm_methods + '&user=' + lastfm_user + '&api_key=' + lastfm_key + '&limit=' + lastfm_limit + '&format=json';
$.getJSON(lastfm_json, function(data) {
var html = '';
var song = data.recenttracks.track[0].name,
artist = data.recenttracks.track[0].artist["#text"],
url = data.recenttracks.track[0].url,
cover = data.recenttracks.track[0].image[0]['#text'];
html += '<p>' + song + ' by ' + artist + '<br /><br /><img src="' + cover + '" style="display: block; width: 96px; height: 96px;" /></p><p>Share on Twitter</p>';
$('#recent-tracks').append(html);
});
//]]>
</script>
<div id="recent-tracks"></div>

Get part of the current URL using Javascript

fI'm developing a simple and small search in a Wordpress page using a $_GET variable in the url passed by javascript:
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = document.URL+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
So, the url to search is: MYURL/?page_id=51&pesquisa=test
Of course, the page_id is variable. If I search again, the URL is going to be: MYURL/?page_id=51&pesquisa=test&pesquisa=new, what is wrong.
How could I get just the MYURL/?page_id=51 using javascript? The window.location.pathname is not what I need.
Thanks.
Anything that searches naively will be vulnerable to problems like this: What if the URL is:
http://example.com/?pesquisa=test&page_id=51
You need to search for and remove the relevant query parameter:
var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;
Try this hopefully it should work
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
try this.
var a = document.URL;
var result = a.substr(0, a.indexOf('&'));
Resources:
Get current URL in web browser
how to grab substring before a specified character jquery or javascript
javascript:
<script type="text/javascript">
function get_query_param(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = function() {
if (get_query_param("page_id") != null) {
alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
}
}
</script>
hope that helps.

JavaScript back button to display previous list

I want create a web application that display a list of items. Suppose I have displayed a list view (say listobject1) of 3 items. when clicked on any of them I get new list view (say listobject2) which its value is according to listobject1. When again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. when I'm now on listobject2 and again when back button is pressed I want to show listobject1. Can anybody tell me how I can do this in JavaScript?
Edit
I'm still study about the stuff but I can't solve this problem yet. In order to clarify my problem now, here's my code:
$(document).ready(function() {
$("#result").hide();
$("input[name='indexsearch']").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $("[name='valueLiteral']").val();
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">"
+ arraySubject[k] + "</span> " + " -> " + v + " : "+
//change object from text to be button form
"<button class = 'searchAgain-button' name = 'searchMore' \n\
value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br> <br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
$("button").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $(this).attr("Value");
//var $textInput = "G53SQM";
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
var searchMore = "searchMore";
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">" + arraySubject[k] + "</span> " + " -> " + v + " : "+ " <button class = 'searchAgain-button' name = " +searchMore + " value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br><br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
At first, user only see one button name "valueLiteral". After user perform 1st search, the result is return in a form of JSON and eventually put in stmt[] to display, which at this state the second button was create as a clickable-result which will automatically take the value of result and do second search if user click the second button.
Now the problem is, I want to add a 3rd HTML button name "back" to make the web display the previous result in stmt[] if user click on the button.
Hope this helps in clarify the problems, I'm still doing a hard work on this stuff since I'm a newbie in JavaScript. Appreciate all helps.
This is what you want almost exactly the way you want it.
You'll have to use history.pushState to push these fake events into the history.
Alternatively, you can use location.hash to store the current object, and update the hash every time you display a new list. Then onhashchange find the hash and display the appropriate list.
See http://jsfiddle.net/cFwME/
var history=[new Array(),new Array()];
history[0].id="#back";
history[1].id="#next";
Array.prototype.last=function(){
return this[this.length-1];
}
$('#list>li:not(:first)').click(function(){
if(!history[0].length || history[0].last().html()!=$('#list').html()){
history[0].push($('#list').clone(true,true));
$(history[0].id).prop('disabled',false);
history[1].length=0;
$(history[1].id).prop('disabled',true);
}
$('#list>li:first').html('This is List '+$(this).index());
});
$('#back').click(getHistory(0));
$('#next').click(getHistory(1));
function getHistory(n){
return function(){
if(!history[n].length){return false;}
history[(n+1)%2].push($('#list').replaceWith(history[n].last()));
history[n].pop();
$(history[(n+1)%2].id).prop('disabled',false);
if(!history[n].length){$(history[n].id).prop('disabled',true);}
}
}
Check out jQuery BBQ - http://benalman.com/projects/jquery-bbq-plugin/

Get the parameter string in javascript using jquery

I have these links :
Block 1 :
Adapters
Battery
After click on the link in Block1 , then I start to click on Block2:
Block 2 :
<img src ="/Content/Images/Top/searchbutton.png"/>
I can get the parameter value such as dep=56,cat=654 by using these jquery.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null){
return "";
}else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function SearchClick() {
var cur_url = window.location.href;
var depId = getParameterByName("dep");
var catId = getParameterByName("cat");
var searchStr = getParameterByName("search");
var url_add = "";
if (depId != "") {
url_add += "&dep=" + depId;
}
window.location = "/Products?tab=2"+ url_add;
}
But now I exchanged the link in Block 1 with
<a href='javascript:void(0);' dep='" + work.ID + "'>" + work.ProName + "</a>
//it works well
So how can I get the value of dep in Block 1 by using javascript or jquery when I click on the the Block 2 link?
Thanks so much for all your answers.
It would be best if you put an ID on the A tag, like so:
<a id="myLink" href='javascript:void(0);' dep='" + work.ID + "'>" + work.ProName + "</a>
then you could use the following JQuery to get the value of work ID:
$("#myLink").attr("dep")
or plain old Javascript like so (assuming you've still got that ID on the A tag):
document.getElementById("myLink").getAttribute("dep")
EDIT: I've put it in the click for you, here is all my code:
<a id="block1Link" href='javascript:void(0);' dep="56">Adapters</a>
<br />
<br />
Click
<script type="text/javascript">
function SearchClick() {
var department = $("#block1Link").attr("dep");
alert(department);
}
</script>
Or if you want to use Javascript swap the var department line with this line:
var department = document.getElementById("block1Link").getAttribute("dep");

Categories

Resources