Getting text value when a list is clicked - jQuery Mobile - javascript

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

Related

jQuery not extracting text values clicked properly

I am using a php script to extract values from the database as follows,
<div class="col-md-4" >
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while ($output = mysqli_fetch_array($rslt)) {
?>
<li class="nav" id="test" style= "text-decoration: none;">
<a href="postad" >
<?php echo $output['Classify'].'<br/>'; } ?>
</a>
</li>
</div>
<div class="col-md-4" id="testing">
</div>
this code gives me below result:
General equipment
Test equipment
Renewable energy
Engineering Services
Trade services
Below is the jQuery bit:
<script>
$(document).ready(function(){
$("#test").click(function(){
var classprod = $(this).text();
$("#testing").text(classprod);
event.preventDefault();
})
});
</script>
However this only outputs line-1 but nothing else i.e. General equipment.
What changes do I have to make to my javascript code in order to be able to display any item clicked?
Little errors, but easy to solve. Your php loop leave a lot of tags opened, an closes just one, then you should use a Class instead on an Id for multiple elements.
Another tip is that you should open and close the ul tag before your list.
HTML
<div class="col-md-4" >
<ul>
<?php
$qry = "SELECT * FROM upperbit_categories";
$rslt = mysqli_query($dbc,$qry);
while($output = mysqli_fetch_array($rslt)){?>
<li class="nav test" style= "text-decoration: none;"><a href="postad" ><?php echo $output['Classify'];?></a></li>
<?php };?>
</ul>
</div>
<div class="col-md-4" id="testing"></div>
JS
<script>
$(document).ready(function(){
$(".test").on('click',function(event){
event.preventDefault();
var classprod = $(this).text();
$("#testing").text(classprod);
})
});
</script>
Also, I don't know what you're doing, but consider to use $(".test a") instead of $(".test")
In General, id of HTML elements should be unique, this requirements can be realized when using jQuery or JavaScript. In your code, you used id="test" for the li element inside a loop, and then you referenced to them using $("#test") then, only first li works due to uniqueness of id.
you can use class instead of id.

jQuery selector problems

I have some tabs' info rendered with handlebars and here is my HTML:
<ul class="nav nav-tabs" id="tabsId">
<script id="tabs-template" type="text/x-handlebars-template">
{{#each Tabs}}
<li data-tab-content={{Id}}>{{Name}}</li>
{{/each}}
</script>
</ul>
<div id="tabsContentId">
<script id="tabs-content-template" type="text/x-handlebars-template">
{{#each Tabs}}
<div class="tab-content" data-tab-content="{{Id}}">{{Content}}</div>
{{/each}}
</script>
</div>
And now I'm writing a function that will fill my future form when I double click on any tab. I've only managed how to get id and I don't understand how to get name and content values. I've tried to use jQuery .text() function, but I've failed. Here is my function:
$(function() {
$("#tabsId").on("dblclick", "li", function(evt) {
evt.preventDefault();
var id = $(this).data("tabContent");
//var name = ?
//var content = ?
$('#inputIndex').val(id);
//$('#inputTitle').val(name);
//$('#textareaContent').val(content);
});
});
var id = $(this).data("tab-content");
var name = $(this).text();
// Get the content from the nth element in the other list (using the index of the LI clicked)
var content = $('#tabs-content-template .tab-content').eq($(this).index()).text();
Note: this only works as the same collection is used for both the LIs and the tab DIVs. Otherwise you will need to find it via the data-tab-content attribute.
Use $(this).text() then you can get the name in the dbclicked li.
Use $('#tabsContentId div[data-tab-content="' + id + '"]'); so you can get the target div which has an attribute data-tab-content and value is the id you previously retrieved.
$(function() {
$("#tabsId").on("dblclick", "li", function(evt) {
evt.preventDefault();
var id = $(this).data("tabContent");
var name = $(this).text();
alert("Name is :" + name);
var targetDiv = $('div.tab-content[data-tab-content="' + id + '"]');
var content = targetDiv.text();
alert("Content is :" +content);
$('#inputIndex').val(id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav nav-tabs" id="tabsId">
<li data-tab-content="t1">I'm Name</li>
</ul>
<div id="tabsContentId">
<div class="tab-content" data-tab-content="t1">Here's content</div>
</div>
Not exactly sure what you're after, but this would get the inner HTML of the first <a> element with href="#" inside the clicked element:
var name = $(this).find('a[href="#"]').first().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);
});

How to show content based on url parameter via 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"

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