Get value of li clicked as a link - javascript

I got couple of li elements and using them as a links to welcome.php. In welcome.php I need to know which one was clicked.
<ul>
<li><a href='welcome.php'>sport</a></li>
<li><a href='welcome.php'>relax</a></li>
<li><a href='welcome.php'>gym</a></li>
</ul>
I can't use jquery. Is there any other way to do this?

The simplest way to do this might be to append a query parameter to your links:
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>

you can incorporate the value in the links and get them with PHP like this
<a href="welcome.php?x=sport">
Where x is the variable you're going to get by using this in your php:
$x = $_GET["x"];
You'd need to do the same with all other links. but you only need to get the value once ofcourse
I was a little bit too late with posting this, but I think mine might have a better explaination so I'm keeping it

You can use $_GET for post value of li
I prepare an example for you
index.php
<form action="welcome.php" method="post">
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
</form>
welcome.php
$var = $_GET["var"];
echo $var;

I have prepare one solution for you using simple html and Javascript :
<html>
<body>
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
</body>
<script>
var el = document.getElementById('sport');
el.onclick = showMsg1;
var el = document.getElementById('relax');
el.onclick = showMsg2;
var el = document.getElementById('gym');
el.onclick = showMsg3;
function showMsg1() {
//alert('Sport Clicked!');
//Do what ever you want after click of "sport"
window.location = "welcome.php?type=sport";
return false;
}
function showMsg2() {
//alert('relax Clicked!');
//Do what ever you want after click of "relax"
window.location = "welcome.php?type=relax";
return false;
}
function showMsg3() {
//alert('Gym Clicked!');
//Do what ever you want after click of "Gym"
window.location = "welcome.php?type=gym";
return false;
}
</script>
I am sure this will helpful to you. Thank you :)

Related

Uncaught Reference Error and JS functionality

I've been looking at this for a while and I can't seem to find a proper solution for it.
Here is part of my code:
<li style="float: right;">Themes
<ul>
<?php
$db=mysql_connect('localhost','root','');
if(!$db) {
die('Could not connect: '.mysql_error());
}
$connection_string=mysql_select_db('somedb',$db);
$selectSQL='SELECT * FROM color_patterns';
$queryset=mysql_query($selectSQL);
$num=mysql_num_rows($queryset);
if(0==$num) {
echo "No record";
exit;
} else {
while($row=mysql_fetch_assoc($queryset)) {?>
<li onclick="liPosition()">
<?php echo($row['name']);?></li><?php
}
}
?>
</ul>
</li>
this is a list item that contains a drop down list. To populate the dropdown list I make a call to my database and for each row in the table I add an li element to the dropdown. I want to retrieve more information from the db based on which li the user clicks so I made a JS function that should get me the index of the li that's clicked on, (The li index corresponds to the id of another table I want to retrieve information from):
<script>
function liPosition() {
var index = $(this).parent().children().index(this);
alert("You clicked item " + index);
});
</script>
When I click on the li I get an error:
Uncaught ReferenceError: liPosition is not defined after some research I found that I can't pass onclick listeners here but I don't know how to find the index of the li in the while loop otherwise. Is there a way to find the index of an li element in a list that's been generated with a while loop? Any help would be greatly appreciated, Thank you.
Why not remove the inline JavaScript and go full jQuery?
PHP - use a class to identify the clicked item;
while($row=mysql_fetch_assoc($queryset)) {?>
<li class="list_item">
<?php echo($row['name']);?></li><?php
}
jQuery - The selector is the list item's class;
<script>
$(document).on('click', '.list_item', function() {
var index = $(this).id;
alert("You clicked item " + index);
});
</script>
In addition: please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
you can send the this reference as a parameter to the function.
<li onclick="liPosition(this)">
and then add the parameter to your function.
<script>
function liPosition(listitem) {
var index = $(listitem).parent().children().index(listitem);
alert("You clicked item " + index);
};
</script>
FYI, you also have a small typo with an extra ) at the end of your function definition });
<script src="http://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<li onclick="liPosition(this)">item 1</li>
<li onclick="liPosition(this)">item 2</li>
<script>
function liPosition(listitem) {
var index = $(listitem).parent().children().index(listitem);
alert("You clicked item " + index);
};
</script>

Confirm Deletion Dialog Box

I have the following line of code
$product_list="$product_list $id - $product_name - $date_added <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br/>"
and
if(isset($_GET['deleteid']))
{
echo 'Do you really want to delete this item with ID of '.$_GET['deleteid']. '? Yes | No';
exit();
}
How can I make it appear as a dialog box and do you think using a dialog box instead of going to the confirmation page will be a good option?
UPDATE
I tried the following but when ever deleteid gets set it creates another new delete link how can I make the existing delete link show the confirm box?
if(isset($_GET['deleteid']))
{
echo 'Delete';
}
UPDATED try
$product_list="$product_list $id - $product_name - $date_added <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$_GET[deleteid]' onClick='return confirm(\'Do you want to delete?\');'>Delete</a><br/>"
Doesn't seem to be working.
<script>
var el = document.getElementById('deleteLink');
el.onclick = reallyDelete();
function reallyDelete(){
var verifyDelete = confirm("Really wanna delete?");
if (verifyDelete == false) {
e.preventDefault();
}
}
</script>
Then you'd of course have to add the ID (deleteLink) to the A link, and this will also only work if there is one link to "delete" otherwise you might need to use onClick, but I would recommend googling around for a tutorial on how to achieve the best solution for you.
(There is also still Bootstrap)
UPDATE
Replace
<a href='inventory_list.php?deleteid=$id'>delete</a>
with
Delete
And delete this:
if(isset($_GET['deleteid']))
{
echo 'Delete';
}

How to use javascript to change content value?

I am currently developing a system which user can only view the name with the start character.
Below is the example :
When I click on the "A" link, the below table will show the name which start from "A" and will not shows the rest of the records.
I am trying to use href to pass operation to my php but it is not flexible to do so. Therefore, I looking for javascript to help me go through this. What I want to do is the page will not refresh and will direct change the content when I click on the A~Z link.
This is my HTML code :
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
This is my php page which execute data from table :
$rsa = array();
$sqladded = false;
$appliedfilter = array();
if($_REQUEST['op'] = ''){
$record = 'A';
}
else{
$record = $_REQUEST['op'];
}
$stmt = $getuser->getuser($record);
if ($rs = $db->Execute($stmt))
{
$arrResult = array();
while($rsa = $rs->FetchRow())
{
array_push($arrResult, array(
"name" => $rsa['name'],
"mobile_no" => $rsa['mobile_no'],
"email" => $rsa['email'],
"address" => $rsa['address'],
"current_professional" => $rsa['current_professional'],
"others" => $rsa['others']
));
}
$tpl->display("alumni-listing.html");
}
And this is my SQL statement :
function getuser($record)
{
global $db;
$arrResult = array();
$stmt = "SELECT * FROM "._CONST_TBL_ALUMNI." WHERE name LIKE ".$record."%";
if($rs = $db->Execute($stmt))
{
$arrResult = $rs->GetArray();
}
return $arrResult;
}
Hope someone can help me.
Thanks in advanced.
Anyhow you have to use the calls to the PHP page.
If not then you can make a the 1st call load all data (A-Z) and then display the connects with just a click. But then your 1st call would be big and it will take time to load if data is greater.
You can use Ajax calls.
Structure your HTML as this way.
<li><a href="#" class='ajaxCaller>A</a></li>
<li><a href="#" class='ajaxCaller>B</a></li>
<li><a href="#" class='ajaxCaller>C</a></li>
<li><a href="#" class='ajaxCaller>D</a></li>
<li><a href="#" class='ajaxCaller>E</a></li>
<li><a href="#" class='ajaxCaller>F</a></li>
The Ajax calls should be
$('a.ajaxCaller').click(function(event){
event.preventDefault();
var x=$(this).text();
$.ajax({
url: "alumni-listing.php",
data: {op:x}
}).done(function() {
// You can have your code to set the returned page, to the specific div.
});
});
I have made lots of project like the one you ask. Learning to use jQuery a javascript framework would be the best solution to solve the task. jQuery made ajax process very simple using jQuery.post().
So the way I see it, your problem boils down to dynamically querying the database on a Dom-event (i.e, through javascript) and not navigating to a different page. Which is lucky, because AJAX was developed pretty much for this - smaller 'refreshes'.
Use JS to trigger a php request, and parse the return
Check out jQuery's Post. I am sure it can be accomplished without, so please edit the question if jQuery is a no-no. If you change your php page to just echo a JSON of the result, and call if from JS, you can parse the JSON and display it in the html page.
HTML
<li><a class="listing-filter" href="alumni-listing.php?op=a">A</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=b">B</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=c">C</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=d">D</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=e">E</a></li>
<li><a class="listing-filter" href="alumni-listing.php?op=f">F</a></li>
Javascript
$('.listing-filter').click(function (e) {
var $filter = $(e.currenttarget),
filterValue = $filter.html();
RefreshPageWithData(filterValue);
});
function RefreshPageWithData( filterBy ) {
var data = {
op: filterBy,
};
$.post(pathname-on-server.php, data, function (response) {
//Parse the response
var results = JSON.parse(response);
//Construct the DOM
var newHtml;
//Append it to existing element
$('#container').html(newHtml);
});
Please note that anything you echo in the php page is the response passed back to the JS callback. So, a simple idea might be to echo json_encode($arrResult). I suggest having one index.php that serves the file as you do above, and another that does similar tasks but echoes the retrieved data. This avoids a double-server request for the homepage.

Simple quiz - how to get clicked values and send it to php

I have to write a simple quiz app. As I picked it after someone this is what I have.
There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc.
However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct.
The code looks something like this:
<form action="result.php">
<div class=“quiz>
<div class=“question”> Some question ?
<ul>
<li><a href=“#”>Answer A</a></li>
<li><a href=“#”>Answer B</a></li>
<li><a href=“#”>Answer C</a></li>
</ul>
</div>
[… more question here …]
<div class="question">Last question ?
<ul>
<li>Answer A</li>
<li>Answer B</li>
<li>Answer C</li>
</ul>
</div>
</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>
So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.
There are many ways to accomplish this. Here's an easy one:
add a
<input type="hidden" name="questions[]" value="" />
inside each .question DIV
update the value of this input when one of the links are clicked:
$('.question a').on('click', function(){
var answer = $(this).text();
$(this).parents('.question').find('input').val(answer);
});
put a request method on your form, let's say POST
Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].
I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).
Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.
I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/
Basically something like:
function verify(answers) {
jQuery.ajax("http://yoursite/verify.php?answers="+answers,
{ async: true,
complete: function(response, status){
// e.g.
alert(response.text);
}
};
};
This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:
function retrieveQuestions() {
//TODO: get them from a json-request like http://yourquizz/quizz1/questions
return [{ text: "what if Zoo went to Blohom in a Flurk?",
options: { a: "he frunts and vloghses",
b: "the Blohom doesn't snorf anymore" }
},
{ text: "how many this and that",
options: { a: "1", b: "2", c: "14" }
}
];
};
// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
jQuery("#questions").append(createQuestionElement(question));
});
// what does a question element look like:
function createQuestionElement(question){
var li=document.createElement("li");
var options = [];
Object.keys(question.options).forEach(function(key){
var o = document.createElement("div");
jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
li.appendChild(o);
});
return li;
}
Your php backend verify.php script will check the arguments and return the result in json format, e.g.:
$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");
(provided your answers are stored in an array $answers.
Yet another solution to the problem:
jsFiddle
We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.
$('.question a').on('click', function (e) {
e.preventDefault();
var self = $(this);
var ans = self.parent().index() + 1;
answers.push(ans);
var hasNext = nextQuestion();
if (!hasNext) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"answers": answers
}
}).done(function (response) {
response = 'Stuff you output with PHP';
$('body').append('<p> Result: ' + response + '</p>');
});
}
});

How can I get the data-id attribute?

I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
</a>
</li>
</ul>
To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use
$(this).attr("data-id") // will return the string "123"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
Read this documentation
Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will not be reflected in the data() jQuery function. You have to adjust it via data() function as well.
<a data-id="123">link</a>
JavaScript:
$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321
If you are not concerned about old Internet Explorer browsers, you can also use HTML5 dataset API.
HTML
<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>
JavaScript
var myDiv = document.querySelector('#my-div');
myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset
You can also use:
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
This piece of code will return the value of the data attributes. For example: data-id, data-time, data-name, etc.
I have shown it for the id:
Click
JavaScript: Get the value of the data-id -> a1
$(this).data("id");
JQuery: This will change the data-id -> a2
$(this).data("id", "a2");
JQuery: Get the value of the data-id -> a2
$(this).data("id");
HTML
<span id="spanTest" data-value="50">test</span>
JavaScript
$(this).data().value;
or
$("span#spanTest").data().value;
ANS: 50
Accessing the data attribute with its own id is a bit easy for me.
$("#Id").data("attribute");
function myFunction(){
alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
var id = $(this).dataset.id
works for me!
I use $.data:
//Set value 7 to data-id
$.data(this, 'id', 7);
//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Using jQuery:
$(".myClass").load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
Try
this.dataset.id
$("#list li").on('click', function() {
alert( this.dataset.id );
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />
</a>
</li>
</ul>
for pure js
let btn = document.querySelector('.your-btn-class');
btn.addEventListener('click',function(){
console.log(this.getAttribute('data-id'));
})
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.
$('#select').on('change', function(){
let element = $("#visiabletoID");
element.val($(this).find(':selected').data('record'));
});
For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See .tooltip('dispose').
HTML 5 introduced dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset, the browser compa
But for older browser you can use getAttribute method to get the data-* attributes.
const getDataAttr = (id) => {
if(currentNode.dataset) return currentNode.dataset[id];
return currentNode.getAttribute("data-"+id);
}
The reason to use dataset is constant lookup time, get attribute would not be a constant time lookup, it'll go through all the attributes of the html element and then return the data once it'll find the exact attribute match.
The reason to provide this answer is that nobody mentioned about the browser compatibility and lookup time with the given solution, although both of these solutions are already given by people.
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});

Categories