How to show content based on url parameter via JavaScript? - javascript

[Update] code I have edited
First, the plain HTML :
<ul>
<li>coke</li>
<li>buble-tea</li>
<li>milk</li>
</ul>
Second, link page (javascript_accord.php) contain javascript:
<html>
<head>
<script type="text/javascript" src="development-bundle/jquery-1.3.2.js"></script>
<script language="javascript">
$(document).ready(function() {
var option = 'coke';
var url = window.location.pathname.split('/');
option = url[3];
showDiv(option);
});
function showDiv(option) {
$('.boxes').hide();
$('#' + option).show();
}
</script>
</head>
<body>
<div class="boxes" id="coke">Coke is awesome!</div>
<div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
<div class="boxes" id="milk">Milk is healthy!</div>
<p>
I change my mind:
<ul>
<li>Coke</li>
<li>Bubble Tea</li>
<li>Milk</li>
</ul>
</p>
Back to main page
</body>
</html>
I found some tutorial about 'show/hide' content based on URL parameter via JavaScript.
But I stuck when I change a part of the JavaScript code.
Here are the code that I learned from the tutorial.
First page contain some links to other page:
If you had to choose a drink, what would you choose:
<a href="/demo/demo-show-hide-based-on-url.html?option=coke"
<a href="/demo/demo-show-hide-based-on-url.html?option=bubble-tea"
<a href="/demo/demo-show-hide-based-on-url.html?option=milk
And here is the code contain in linking page (/demo/demo-show-hide-based-on-url.html) :
<div class="boxes" id="coke">Coke is awesome!</div>
<div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
<div class="boxes" id="milk">Milk is healthy!</div>
<p>
I change my mind:
<ul>
<li>Coke</li>
<li>Bubble Tea</li>
<li>Milk</li>
</ul>
</p>
Back to main page
And the javascript :
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var option = 'coke';
var url = window.location.href;
option = url.match(/option=(.*)/)[1];
showDiv(option);
});
function showDiv(option) {
$('.boxes').hide();
$('#' + option).show();
}
</script>
It works greatly, but when I try to change the link page from
href="/demo/demo-show-hide-based-on-url.html?option=coke"
into something like this :
href="/demo/demo-show-hide-based-on-url.html/option/coke"
And change the url variable in javascript from
var url = window.location.href;
option = url.match(/option=(.*)/)[1];
to
var url = window.location.pathname.split('/');
option = url[3];
And all content in
<div class="boxes" id="...">
appear.
It supposed to be only selected one will appear. I have tried
var url = window.location.pathname.split('/');
option = url[3];
in simple JavaScript to check whether it will catch the right or value or not. And it does return the right value (coke, milk, bubble-tea).
So, what went wrong?
I hope somebody understand this problem and help.

path to jquery is wrong. Can you please check if jquery library is loading?
jquery will be loaded from javascript_accord.php/option/coke/development-bundle/jquery-1.3.2.js
Please make the path to library absolute. That should do :)

I believe that window.location will return the full URL of the page, so you're not just working with the /demo/demo-show-hide-based-on-url.html/option/coke part.
I'd simply change the regular expression instead to replace the = with a /, like so:
option = url.match(/option\/(.*)/)[1];

"/demo/demo-show-hide-based-on-url.html/option/coke".split('/')[3] will return option and not coke
there are 5 entries in the array, because there is an empty string before the first '/':
"",
"demo",
"demo-show-hide-based-on-url.html",
"option" and
"coke"

Related

Finding onClick event if is set for the element or the parents

I want to change a HTML+JS template behavior but i don't want to re do things which are already done. assume we have a hierarchy of elements and looks like the inner one is calling a function on it's onclick event. but when i select it on the chrome inspector console and check if it has anything for the onclick it returns null i think it's developed in a more general way or possibly on other property?
What i want is to find that function wrap it in mine and call it after doing something else.
The hierarchy is like below:
<ul> <li data-id="1234"> <div> the button </div> </li> ... </ul>
whenever the button is pushed the data-id is sent to the server via ajax.
I played a little bit with es6 and did the expected result: https://codepen.io/omgitsevan/pen/yxrVVM
but basically, the code is the following:
Javascript
document.addEventListener('click', (evt) => {
function getDataAttr(node, attrValue) {
if (!node.getAttribute(attrValue)) {
return getDataAttr(node.parentNode, attrValue)
}
console.log(node.getAttribute(attrValue))
}
getDataAttr(evt.target, 'data-id');
})
HTML
<ul>
<li data-id="1234">
<div> the button </div>
</li> ... </ul>
I hope it will work
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$(".data").click(function(){
var data = this.parentNode.parentNode.getAttribute("data-id");
$.ajax({
url:"url",
data:{'data':data},
type:"post",
success:function((){
});
})
});
});
</script>
</head>
<body>
<li data-id="1234"> <div> <a class="data" onclick = abc(event)>the button</a> </div>
</body>
</html>

can't get data attribute with jquery

I am trying to retrieve data-cost("#packages") and append it to #form next to Ticket-price. I am not getting any errors in console. I can't seen to understand what went wrong.
JS:
<script src="jquery-1.11.2.js"></script>
<script>
$(document).ready(function()
{
var price=$("#packages").data("cost");
var amount=$("<span>"+price+"</span>");
$("#form").next().next().append(amount);
});
</script>
HTML:
<div id="packages">
<h2><u>Tourism Packages:</u></h2>
<ul>
<li data-name="Southern Travels">Travels Name: Southern Travels</li>
<li data-cost="2000">Cost per person: 2000</li>
<li>Duration: 3 days & 4 nights</li>
</ul>
</div>
<div id="form">
<label>Number of persons </label>
<input id="input"type="text"/ autofocus>
<p id="ticket-price">Ticket Price</p>
</div>
For this to work as it is, you must edit your HTML as following:
<div id="packages" data-name="Southern Travels" data-cost="2000">
<h2><u>Tourism Packages:</u></h2>
<ul>
<li>Travels Name: Southern Travels</li>
<li>Cost per person: 2000</li>
<li>Duration: 3 days & 4 nights</li>
</ul>
</div>
Either that, or access the data properties of the <li> elements instead of the div#packages (i.e #packages ul li instead of #packages)
$(document).ready(function() {
// Targeting 2nd li element inside #packages
var price=$("#packages li").eq(2).data("cost");
// create a span element with text 'price'
var amount=$("<span>"+price+"</span>");
// append as last child of the form
$("#form").append(amount);
});
You need to look for your data attribute by name - and look at the LI's.
You also need to build your html string and append it properly to the #ticket-price
WOKING EXAMPLE (FIDDLE): http://jsfiddle.net/ojLo8ojz/
JS:
$(document).ready(function(){
var price = $("#packages li[data-cost]").attr("data-cost");
var amount = "<span> "+price+"</span>";
$("#ticket-price").append(amount);
});

Getting text value when a list is clicked - jQuery Mobile

I have a list which is being loaded from a php file I am trying to get text inside this list. When i click this list, the console gives me a referenceError. I am going to show just HTML code with comments where data is added from php.
<div data-demo-html="true">
<ul data-role="listview" data-theme="a" data-split-theme="b" data-split-icon="plus" data-inset="true" id="courselist">
<!-- Data below loaded from PHP-->
<li id="clist">
<a href="#page">
<h2> text loaded here </h2>
</a>
</li>
</ul>
<!-- Data loading finished from PHP -->
</div>
<script>
$(function(){
var desc;
$('body').on('click','clist',function(){
desc = $(this).text();
console.log(desc);
});
});
</script>
Your selector is wrong as clist is id of li element, so use '#clist' instead of 'clist':
<script>
$(function(){
var desc;
$('body').on('click','#clist',function(){
desc = $(this).text();
console.log(desc);
});
});
</script>
See jQuery Selector API for more information
You missed id # selector
HTML <li id="clist">
$('body').on('click','#clist',function(){
^^^^^
desc = $(this).text();
console.log(desc);
});
Read Jquery Selector

Displaying jQuery checkbox selection

This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.

I am having a few problems trying to create a jquery live search function for basic data set?

I am designing a simple jquery live search function within a widget on a site i'm developing. I have borrowed some code I found and it is working great. The problem is though that instead of using a list like this:
<ul>
<li>Searchable Item 1</li>
<li>Searchable Item 2</li>
etc
I am using a list like this:
<ul>
<li>
<a href="#">
<div class="something>
<img src="something.jpg">
<p>Searchable Item 1</p>
</div>
</a>
</li>
etc.
As you can see the text I want to search is in the p tag. The functions I have used are searching all the other stuff (a href, div, img) and matching text found in those tags as well as the item within the p tag. Sorry if my explanation is a bit confusing but I will show you an example of the code here:
//includes im using
<script type="text/javascript" src="js/jquery-1.7.min.js" ></script>
<script type="text/javascript" src="js/quicksilver.js"></script>
<script type="text/javascript" src="js/jquery.livesearch.js"></script>
//document ready function
$(document).ready(function() {
$('#q').liveUpdate('#share_list').fo…
});
//actual search text input field
<input class="textInput" name="q" id="q" type="text" />
//part of the <ul> that is being searched
<ul id="share_list">
<li>
<a href="#">
<div class="element"><img src="images/social/propellercom_icon.jpg… />
<p>propeller</p>
</div>
</a>
</li>
<li>
<a href="#">
<div class="element"><img src="images/social/diggcom_icon.jpg" />
<p>Digg</p>
</div>
</a>
</li>
<li>
<a href="#">
<div class="element"><img src="images/social/delicios_icon.jpg" />
<p>delicious</p>
</div>
</a>
</li>
</ul>
also here is the jquery.livesearch.js file I am using
jQuery.fn.liveUpdate = function(list){
list = jQuery(list);
if ( list.length ) {
var rows = list.children('li'),
cache = rows.map(function(){
return this.innerHTML.toLowerCase();
});
this
.keyup(filter).keyup()
.parents('form').submit(function(){
return false;
});
}
return this;
function filter(){
var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
if ( !term ) {
rows.show();
} else {
rows.hide();
cache.each(function(i){
var score = this.score(term);
if (score > 0) { scores.push([score, i]); }
});
jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
jQuery(rows[ this[1] ]).show();
});
}
}
};
I believe the problem lies here:
var rows = list.children('li'),
cache = rows.map(function(){
return this.innerHTML.toLowerCase();
});
it is just using whatever it finds between the li tags as the search term to compare against the string entered into the text input field. The search function actually does work but seems to find too many matches and is not specific as I am also using a quicksilver.js search function that matches terms that are similar according to a score. When I delete all the other stuff from the li list (a href, img, div, etc) the search function works perfectly. If anyone has any solution to this I would be really greatful, I have tried things like:
return this.children('p').innerHTML but it doesn't work, I'm ok with PHP, C++, C# etc but totally useless with javascript and Jquery, they're like foreign languages to me!
In the jquery.livesearch.js file I believe you can replace this line:
var rows = list.children('li'),
with:
var rows = list.children('li').find('p'),
This should make it so the livesearch plugin will only search the paragraph tags in your list.
You will need to change the .show()/.hide() lines to reflect that you are trying to show the parent <li> elements since you are now selecting the child <p> elements:
Change:
rows.show();//1
rows.hide();//2
jQuery(rows[ this[1] ]).show();//3
To:
rows.parents('li:first').show();//1
rows.parents('li:first').hide();//2
jQuery(rows[ this[1] ]).parents('li').show();//3

Categories

Resources