Settings Selector Dynamically in JQuery - php

I have a table whose values are being generated dynamically with PHP, including the id and name attributes (e.g. id="question_".
How can I set an element attribute with this in mind? For example, I have a div whose text will change after a successful ajax call, but the id is dynamic.
I have tried making the following test function, and calling it on an onclick event:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#div').html('test');
}
But that does not work. How can make the value of variable 'div' the selector?

The problem with your example is that div is a variable, not a string; so the following will work:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#' + div).html('test');
}
Or even:
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}
Another approach would be to utilize classes, and add a known class to your elements. Without seeing the full HTML, I can't provide a full example, but something like this would be the way to go:
$('.yourCommonClass').bind('click', function () {
var that = this;
jQuery.get('/accept.php', {
id: this.id
}, function (msg) {
$(that).html('Accepted!');
});
});
Bearing in mind that jQuery.get parameters are the target url, optional data attributes that are encoded in the request, and then a callback function.

you defined div as a variable then used it as a string try concatenating it instead
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+ div).html('test');
}
or shorten like this
function approve(question_id)
{
$('#suggestion_status_' + question_id).html('test');
}

$('#suggestion_status_' + question_id).html('test');

$('#suggestion_status_' + question_id)

I think you want this:
function approve(question_id)
{
var div = 'suggestion_status_' + question_id;
$('#'+div).html('test');
}

this. $('#suggestion_status_' + question_id).html('test');

Related

How to get variable from url for .js file?

Example: Suppose the current page url(window.location.href) is http://example.com/page.html
The html page source code is...
<html><head></head><body>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
Now I need to use 'src' variables in script.js
And the script file script.js should return
var a="Ankit"
var b="18"
Can we use something like echo $_GET like in php?
Found this here. If you're using jQuery, this should be helpful.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
This is a javascript function that will return the value in the url of a parameter that you pass to it. In this case, you would call it with
var a = getURLParameter("user");
var b = getURLParameter("ptid");
EDIT: I misinterpreted the original version of your question as asking about getting parameters to the .html page being loaded. I just tested this solution, and it does not work within the .js file itself. However, if you declare your variables in the .js file, and place this in the onLoad event, removing var from in front of a and b, it should assign the variables correctly.
Maybe outdated but a nice piece of code and would exactly do what was asked for in OP
// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
// Find all script tags
var scripts = document.getElementsByTagName("script");
// Look through them trying to find ourselves
for(var i=0; i<scripts.length; i++) {
if(scripts[i].src.indexOf("/" + script_name) > -1) {
// Get an array of key=value strings of params
var pa = scripts[i].src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
}
// No scripts match
return {};
}
Source: James Smith - Extract GET Params from a JavaScript Script Tag
I know it's an old post, but as I was looking for something like that I came across it. The very simple solution I finally adopted is the following one:
<html><head></head><body>
<script>
var a = "Ankit";
var b = 18;
</script>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
If you absolutely want to complicate your life and use Lahmizzar's solution, I would recommend to give an id to your tag script, which avoids a greedy function.
HTML :
<script src="http://example.com/script.js?user=Ankit&ptid=18" id="myScript"></script>
JS :
function getParams(script_id) {
var script = document.getElementById(script_id);
if(script) {
// Get an array of key=value strings of params
var pa = script.src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
// No scripts match
return {};
}
getParams("myScript");

How to get index of input in javascript - can use jQuery

I have an array of inputs generated from js code. I have set the name of the inputs like this: name="myTextInput[]"
How can I get the index of the selected input?
I tried something like:
onClick="oc(this);"
where:
function oc(inp)
{
return(inp.index);
}
but is not working.
I can use jQuery as well
You can use the EACH function in jquery. This will parse through the set of matched elements. You can put a custom function inside that will use the index of each element, as you parse through, as an argument.
$('input').each(function(index){
alert(index);
});
You can also get the value of each input like this:
$('input').each(function(index, val){
alert(index + ' has value: ' + val);
});
see details here: http://api.jquery.com/jQuery.each/
** EDIT **
If you want the value shown in an alert box on click, use the each function and the click function together. Remember to get the real-time value of the input, use $(this).val(). Return index and value data on click:
$('input').each(function(index, val){
$(this).click(function(){
alert(index + ' has value: ' + $(this).val());
});
});
You could get the input like this (not sure if you actually wanted the click event though)...
var inputs = $('input[name="myTextInput[]"]');
inputs.click(function() {
alert(inputs.index(this));
});
Please use the index() method to find the position of an element.
Check out this example: http://jsbin.com/uyucuv/edit#javascript,html
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
$(function() {
$("li").on("click", function() {
alert($(this).index());
});
});
Check the index() documentation here: http://api.jquery.com/index/
Hope this helps!
The "jQuery way" is to avoid onClick="whatever()" and use pure JavaScript separate from the HTML tags. Try this between a pair of <script> tags (note: requires jQuery 1.7 or higher):
$('input').on('click', function() {
var varname = $(this).attr('name'),
$arr = $('input[name="'+varname+'"]'),
idx = $arr.index(this);
alert(idx);
});​
http://jsfiddle.net/mblase75/EK4xC/

How to check for contents of a loaded div tag using jquery load?

I'm working with jqueries address change event and am hitting a roadblock when a user copies and pastes a URL in the browser. I need to fist load a portion of the page that contains a form. I could do this after every pagination call but it seems really ineffecient.
Here is my current code block:
$.address.change(function(e) {
var urlAux = e.value.split('=');
var page = urlAux[0];
var start = urlAux[1];
if (page == "/visits") {
$.address.title("Profile Views");
if (start) {
$('#start').val(start);
// ***** If a user has copied and pasted this URL with a start value then I first need to load visits.php in the main div tag. Is it possible to see if this is loaded or not?
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
}
else {
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () { });
}
}
My attempted work around was this:
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
There must be a better way...this is realoading the same portion of the page (visits.php) with every pagination event. Is there a better way to load URLs and not have them trigger an address change?
Using paul's work around from his comments, but instead of Regex'ing html content in the visits.php form this solution will look for data() attached to #mainID.
Paul's work around notes:
After a bit more hacking I came up with this solution that seems to do
the trick. I'm not sure how good it is but it seems to do the trick. I
now get the main div id and do a regex match on a unique string in the
form. If I don't see it I load the form and then load the results. Not
sure if this is good practice or not but it seems to solve my issue.
Methodology to use .data() instead of a regex search of visits.php's html:
/*check if we're missing visits.php by looking for data() flag*/
if( !($("#main").data()["hasVisitsPhp"]) ){
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
/* we've loaded visits.php, set the data flag on #main*/
$('#main').data("hasVisitsPhp","loaded");
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
}
try window.location.hash instead. Changing the whole href can/will trigger a whole-page reload, while changing just the hash by itself should at most cause the page to scroll.

jQuery - Using :contains for instant search with nested divs/classes?

I have a search box. I'm using jQuery and keyup to filter repeating divs.
Each div looks like this:
<div class="searchCell" id="searchCell' . $id . '">';
<div class="friendName">
// someNameOutputWithPHP.
</div>
</div>
Now, I want to filter based on the name text. If someNameOutputWithPHP contains the search query, the entire searchCell should show(). If it doesn't, the entire searchCell should hide().
This doesn't work, though:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
$(".searchCell > .friendName:contains(" + searchValue + ")").show();
});
});
</script>
EDIT
New problem: I got the divs show() to show how I want. But the :contains isn't working exactly right.
For instance: say one of the name's is Ryan. When I search for 'Ryan', I get nothing. But when I search for 'yan' I get the Ryan div.
What's wrong?
Here's the :contains code:
$(".friendName:contains(" + searchValue + ")").parent().show();
That is because you are hiding the .searchCell and then showing its children .friendName divs, which though get display property will not show up because parent is hidden.
Try this:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
//$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
// OR
//$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
// OR
$(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
});
});
</script>
Your selector
$(".searchCell > .friendName:contains(" + searchValue + ")")
will select all .friendName divs that contain the text from searchValue. That works just fine, but you need to .show() the parent element. Just invoke the .parent() method for that:
$(".searchCell > .friendName:contains(" + searchValue + ")").parent().show();
Demo: http://jsfiddle.net/d3ays/3/
And by the way, you HTML markup looks messed up too. There is a ; behind your div.searchCell for instance.

Print the value in loop in Jquery ready function

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all
I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});
You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.
Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.
What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

Categories