Pulling the string value in Javascript - javascript

So I have this unordered list of items that is made from querying a mysql database
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
I want there to be an onclick event that will pass 'apple' when I click apple and 'orange' when I click orange.
I also want to pass this information to another page through php. So this is my idea for the javascript function.
<script>
function passName(obj){
var pass = "<?php $x= " + obj.getName() + " ?>";
}
function getname(obj){
return 'string';
}
</script>
My Question: is there a method that exists within JavaScript that allows me to pull the raw string value of my unorderedlist without writing my own function? If I have to write my own JavaScript function, is there a way to set the 'name' strings automatically, while the list is populating?

Use JQUERY AJAX for send data into php page
/* Get value from clicked li */
$(function() {
let value = "";
$('ul li').on("click", function() {
value = $(this).text();
console.log(value);
});
/* AJAX for send value into result.php page */
$.post("result.php", {value: value}, function(res) {
console.log(res); // return from result.php page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
result.php
if(isset($_POST['value']) && !empty($_POST['value'])) {
echo $_POST['value'];
}

This is how you can do it. On click you can change the page or do whatever you want. In the new url you can append the fruit value as a parameter to pass it to php
<ul>
<li onclick="fruitsClick('apple')">apple</li>
<li onclick="fruitsClick('orange')">orange</li>
<li onclick="fruitsClick('pear')">pear</li>
</ul>
<script>
function fruitsClick(fruit){
// do whatever you want
window.location.href = "[yourpageurl]?fruit=" + fruit
}
</script>

Related

How can I use jquery events to pass variables to php?

I have a form with a drop-down to select a time for scheduling
I didn't use a selector input, instead I used the following html to make the menu for styling reasons.
<div class="tabs">
<div class="apt-time">
<h3>#Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
Because of this I can't use the POST method to get the data the user clicked on in the menu. So I tried to come up with a solution that could pass a string variable with events to my php page with the GET method in the code below. The if statements are going to be used so the client can't submit the form without clicking on an option in the menu. Is there a way around this without using a selector input?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
Added AJAX functionality below. The script passes POST values to PHP script named textsms.php without refreshing browser.
Updated Code:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
For testing..
textsms.php:
<?php
print_r( $_POST );
?>
You're not defining the get variable in the redirection:
window.location.href = "textsms.php?"+clockTime
The following will store the "clockTime" in the $_GET['time']
window.location.href = "textsms.php?time="+clockTime
Edit: Anyway your JS is not correct.
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
You can use a control variable for this (also defining a css class that show the selected option):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
You need to get the value and pass it to your location properly:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
I like using jquery's on event as it allows you to use load content dynamically so long as you target an external static element.
http://api.jquery.com/on/

How to use a javascript function inside class attribute of an element

I want to create a dynamic 'li' elements and want to assign some classes to the 'li' element by a javascript function based on some parameters in the load of the page
I mean i want the function to run on all the 'li' elements i assign the function to.
something like :
in design
<li class="nav-item someFunction("param1","param2")">
</li>
and the 'someFunction' is a javascript function that returns some classes as a string
to make the 'li' element as follows in the end :
after rendering
<li class="nav-item cssClass1 cssClass2 cssClass3 cssClass4">
</li>
Not exactly how you asked it, but here is how you do it with jquery:
CodePen: https://codepen.io/anon/pen/XeJKVL
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.red{
color:red;
font-size:25px;
}
</style>
<script>
window.onload = function() {
$( "#example" ).addClass("red");
}
</script>
<li id="example">Example</li>
$(document).ready(function(){
$("#ifValueBtn").on("click",function(){
var iFinput=$("#ifValue").val();
if(iFinput==1)
$(".nav-item").addClass("cssClass1");
else if(iFinput==2)
$(".nav-item").addClass("cssClass1 cssClass2");
else
$(".nav-item").addClass("cssClass1 cssClass2 cssClass3");
console.log($(".nav-item").attr("class"));
});
});
.cssClass1{color:red;}
.cssClass2{border:solid 1px #000;}
.cssClass3{font-size:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ifValue" type="number" value="1"/>
<input id="ifValueBtn" type="button" value="Click"/>
<hr>
<ul>
<li class="nav-item">
test
</li>
</ul>
Actually I figured out the answer from you people answered ideas
I create the li items dynamically so I tried to create all the markup for it from database but it didn't work as the functions calls are being copied as string without parsing or compiling it of course
so
I have made the following function :
function someFuncionConvertedItsCodeFromServerSide(parameter1, parameter2,...) {
//somecode that debend on some server side functions, collections, session values, properties
// return css as string
}
and get some parameters from the db as follows in the ajax call example :
$.ajax({
type: 'POST',
url: 'url',
dataType: 'json',
success: function (result) {
for (var i = 0; i < result.array.length; i++) {
var css = someFuncion(result.array[i].id, other parameters .. );
var liItem = "<li class=\"nav-item " + css + " id=\"" + result.array[i].id + "\"> <span class=\"title\" > " + someText + " </span > </li>";
$("#ulId").append(liItem);
}
}
});
so as you can see I created an id for every created li to combine the parameters in one place that can be sent to a javascript function to return the css classes as a string as needed
It's a prototype code of course it needs some modification but that what is done and worked
thank you all guys trying to help I get the idea from our discussion together
tell me If i didn't mark the right answer

Passing a variable from jsp page to servlet

If a user clicks on the following, he will be send to another page via the servlet.
<li><a method="POST" href="ToolServlet?action=goToUserRolesOverview">SOME TEXT</a></li>
I want to send a variable with the submit to the servlet, I came up with this:
<li><a method="POST" href="ToolServlet?action=goToUserRolesOverview">SOME TEXT<input type="hidden" name="user_emailHidden" id="user_emailHidden" /></a></li>
To fill in the hidden 'user_emailHidden', I do the following JavaScript:
console.log("user_email: " + params.user_email); /*Testing only: it works */
document.getElementById("user_emailHidden").value = params.user_email;
The value is set to the hidden variable, I tested this with:
console.log("user_email test: " + document.getElementById("user_emailHidden").value);
This is not working. Any help on how to include the variable with the submit when the user clicks on this item?
Thanks
this way to send variable with the url to the servlet .
javaScript
<script type="text/javascript">
function navigate() {
var userEmail = document.getElementById('user_emailHidden').value;
window.location = '${pageContext.servletContext.contextPath}/ToolServlet?id='
+ userEmail;
}</script>
href
SOME TEXT <input
type="hidden" name="user_emailHidden" id="user_emailHidden"
value="123546" /></a>
Servlet
#RequestMapping(value = "/ToolServlet")
public void getEmailId(HttpServletRequest request) {
System.out.println(request.getParameter("id"));
}
Found the solutions.
For the link, I send the variable with the url to the servlet as so:
<li id="insertUserEmail">SOME TEXT</li>
To add the user-email to the end of the href:
$('#insertUserEmail a').attr('href',function(i,str) {
return str + params.user_email;
});

get the inner value of list item when clicked through javascript

I have a users list, I am retrieving all users from database and listing them as below
<div class="online-users">
<ul id="outer-list">
#foreach($users->getUsers() as $user)
{{--remove white spaces from name--}}
<?php $name = str_replace(' ','-',$user->name);?>
<li onclick="openMessageBox()" id="user" class="inner-list-item">{{$user->name}}</li><br>
#endforeach
</ul>
</div>
This is what I want to achieve when we click on any list item, I want to grab that user's name. But what I have tried so far is
<script>
function openMessageBox(){
var user_id = document.getElementById('outer-list');
user_id=user_id.getElementsByClassName('inner-list-item').innerHTML;
window.alert(user_id);
document.getElementById('message-box').style.display="block";
}
</script>
it only gives me access to the user's name if I use [index] with
user_id=user_id.getElementsByClassName('inner-list-item')[5].innerHTML;
I do not want to explicitly tell the index every time. Is there any way to achieve this?
You need to pass current ref as a parameter.
<input id="theId" value="test" onclick="doSomething(this)" />
// Javascript
function(elem){
var value = elem.value;
var id = elem.id;
...
}
You can pass in the element reference to the function:
<li onclick="openMessageBox(this)" id="user" class="inner-list-item">{{$user->name}}</li><br>
and then get the username by simply reading the element's textContent (this will work for attributes as well, as #rybo111 suggested in the comments):
function openMessageBox(el){
var name = el.textContent;
}
Simple live example:
function openMessageBox(el){
var name = el.textContent;
alert(name);
}
<ul>
<li onclick="openMessageBox(this)">Alice</li>
<li onclick="openMessageBox(this)">Bob</li>
</ul>
And btw. you'll end up having duplicate user IDs on those li elements.

jquery text() not comparing to string

I am using javascript to hide some list Items based on the user role.
I am getting the role from a list item's text(). When I am comparing the $("#activeUser").text() value against a string, it is not working.
HTML Block that I am using in my javascript to get the text() value of a list item.
<ul class="pull-right breadcrumb">
<li>Home <span class="divider">/</span> </li>
<li id="activeUser" class="active"> <?php echo ucfirst($_SESSION['sewafs_user_role']); ?> </li>
</ul>
Javascript
$(document).ready(function () {
var testRole = $("#activeUser").text();
//This block of code works
role = 'Guest';
if (role == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
//This doesn't work why?
if (testRole == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
But if I see the value of the var testRole using alert it prints Guest.
I tried converting the testRole value into string using testRole.toString() / string(testRole) method, but nothing helped.
Please let me know, where I am going wrong. Thanks.
The problem seems to be extra white-spaces in the value that you receive from $("#activeUser").text()
Solution:
You must trim the value and then use it for comparison as:
var testRole = $("#activeUser").text().trim();
OR
var testRole = $.trim($("#activeUser").text());
OR
var testRole = $("#activeUser").text();
testRole = $.trim(testRole);
Any of the above will work.
More info on jQuery trim at this link.
Whitespace test:
If you want to test if you are getting extra white spaces, then try below javascript code:
alert("-" + $("#activeUser").text() + "-");
If you get "" then you dont have whitespaces in your received value.
But if you get spaces after < or before >, then these are white spaces, that are spoiling your party.
Try trimming the string, with $.trim($("#activeUser").text());
There seem to be whitespaces in your element.
You need to trim white spaces at start and end of the string:
var testRole = $("#activeUser").text().replace(/^\s+|\s+$/g,'');
You can see why here: http://jsfiddle.net/AfUZR/1/
Demo
$(document).ready(function () {
var testRole = $("#activeUser").text().trim();
//This doesn't work why?
if (testRole == "Guest") {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
Man, first what do you must do it, it's write correct selector.
$("#request_history_li").hide();
$("#assign_role_li").hide();
you can write
$("#request_history_li, #assign_role_li").hide();
or you can add the same classes of these Elements, that is correct
<ul>
<li class="same_class 1"></li>
<li class="same_class 2"></li>
</ul>
and
$(".same_class").hide();
ok? next:
As concerns your problem, js loaded earlier than you determine the role of, use
$(document).ready(function(){
......
});

Categories

Resources