How to get text field value from another page javascript - javascript

Here My script code
page 1 / index.php
$(document).ready(function(){
$("#list").load("load_list.php");
function reloadlist(){
var total_list = $("#total").val();
$.get('load_list.php', function(data){
var values = $("input[name='total']", data).val();
alert(values);
});
} setInterval(reloadlist, 3000);
})
<body>
<div id="list"></div>
</body>
page 2 / load_list.php
[My query for get the total data]
<input type="hidden" name="total" id="total" value="<?=$total?>">
When i load that index page, and alert value will be undefined. how to get text field value from load_list.php

save the value in a cookie and retrive it in next page

The element is at root level, and the contex selector uses find() internally, and that only works on descendants.
You can avoid any and all issues with elements being descendants or at root level by appending the content to another element, and then using find(), or you could use filter() directly
$.get('load_list.php', function(data){
var values = $('<div />', {html: data}).find("input[name='total']").val();
alert(values);
});
Also, the element has an ID, and it would be more efficient to use that in the selector.

You're in kind of a bad situation since you're just reloading the list after 3 seconds even if the call failed. You should try to clean up the whole idea a bit.
function reloadList = setTimeout(function(){
$.get('load_list.php', function(result){
var value = $(data).filter('#total').val();
alert(value);
reloadList();
});
}, 3000);
reloadList();

Related

Count html elements in ajax returned data

I've got a jquery $.ajax call that returns a set of html from data.html which is like;
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
<div class="blah"><li>test</li></div>
I'd like to count the amount of elements that have a class of .blah and i'm not sure how to do this.
I've tried:
data.html.getElementsByClassName('blah').length
but that obviously doesn't work!
Any suggestions gratefully received!!
Try utilizing .hasClass()
var data = {};
data.html = '<div class="blah item item-wrapper print"></div>'
+ '<div class="blah item item-wrapper digital"></div>';
var len = $.grep($.parseHTML(data.html), function(el, i) {
return $(el).hasClass("blah")
}).length;
$("body").html(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
You should be able to do this using either .filter() or .find(), depending on the exact format of your returned HTML. If the format is is exactly as you have stated, then the following should work:
$.get("data.html", function(data) {
var length = $(data).filter(".blah").length;
});
If there is some sort of wrapper element around your items with class blah, then you would use .find():
$.get("data.html", function(data) {
var length = $(data).find(".blah").length;
});
$('.blah','context').length
Replace context by object in which you want to search

A HTML tag to store "javascript's data"?

I need to write some html with placeholder used for javascript.
ex:
<span><placeholder data-id="42" data-value="abc"/><span>
Later on, a script will access those placeholders and put content in (next to?) them.
<span><placeholder data-id="42" data-value="abc"><div class="Google"><input type="text" value="abc"/></div><span>
But the placeholder tag doesn't exist. What tag can be used? Using < input type="hidden" .../> all over feels wrong.
Creating Custom tag
var xFoo = document.createElement('placeholder');
xFoo.innerHTML = "TEST";
document.body.appendChild(xFoo);
Output:
<placeholder>TEST</placeholder>
DEMO
Note: However creating hidden input fields with unique ID is good practice.
give your span element an id like,
<span id="placeToAddItem"><span>
and then in jQuery,
$('#placeToAddItem').html('<div class="Google"><input type="text" value="abc"/></div>');
or else
var cloneDiv = $('.Google');
$('#placeToAddItem').html(cloneDiv);
Example
The best way to do this, is using <input type='hidden' id="someId" value=""> tags.
Then you can easily access them by using jQuery, and recall the variable or change it.
var value = $("#someId").val(); to get variable or $("#someId").val(value) to change it.
This complete, no jQuery solution allows you to specify the placeholder/replacement html as a string within the element that will be replaced.
EG HTML:
<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>
<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>
<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>
<span data-placeholder="<em>Post JS</em>">Pre JS</span>
<br />
<button id="test">click me</button>
JS:
Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)
var placeholders = document.querySelectorAll('[data-placeholder]'); //or by ids, classnames, element type etc
Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list.
NodeList.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i]);
}
return this;//return self to maintain chainability
};
Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string:
Object.prototype.replaceWith = function(htmlString) {
var temp = document.createElement('div');//create a temporary element
temp.innerHTML = htmlString;//set its innerHTML to htmlString
var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
this.parentNode.replaceChild(newChild, this);//replace old node with new
return this;//return self to maintain chainability
};
Put it all together:
placeholders.each(function(self){
self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});
Another example but here we only replace one specific element with some hard-coded html on click:
document.getElementById("test").addEventListener('click', function() {
this.replaceWith("<strong>i was a button before</strong>");
}, false);
DEMO: http://jsfiddle.net/sjbnn68e/
use the code below :
var x = document.createElement('placeholder');
x.innerHTML = "example";
document.body.appendChild(x);

Find and replace an element in html using jquery

I am trying to load a HTML page into a variable in Jquery, then replace a div element tag in it, so I can get my own id into the div. I am using this way to dynamically add more users in my web app, and then do a batch POST to the back end, and put the info into json.
Here is my html that I am loading.
info.html
<div id="user">
<label>name</label>
<input type="text" name="name">
<br>
<label>email</label>
<input type="text" name="email">
<br>
</div>
I load this with jquery and I want to replace <div id="user"> with something
like <div id="user 1">
I have the following jquery script that has a counter to keep track of what number to append onto the div tag.
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
var content = $('<div>').load("static/info.html"); //using python flask
console.log(typeof(content)); //is of object type
console.log(typeof(content.html())); //is of type string
console.log(content.html());//shows up as an empty string
console.log(content);//prints out the object
content = content.html().replace('<div id="user ">','<div id="user "'+counter+'>'); // doesn't work.
$("#add_div").append(content); //appends correctly if I remove the above line, but all divs have the some id.
});
});
Any suggestions would be great thanks. Also, is the is the best way going about keeping track of how many times a new user is added(as in using a counter and keep track of how they are added, and then do the same when I click submit and create the json)?
.load() is asynchronous. make your changes in side callback.
.load("..",function(){
// your changes
});
Also $( "selector" ).load() is the syntax. So create a div and load content to it.
// modified code structure
<div id"content"></div>
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
$("#content").load("static/info.html",function(){
content = $("#content").html().replace('<div id="user ">','<div id="user "'+counter+'>');
$("#add_div").append(content);
}); //using python flask
});
});
Using JavaScript, you can use the .attr() method to target id, then set its value like so:
$("#content").attr("id", "user_" + counter);
Try an $.each() function for #user like this:
$('#user').each(function(indexNumber){
$(this).replace('<div id="user'+indexNumber+'"></div>');
});

jQuery .html only get last value of JSON

I have a problem with jQuery("#someID").html. It only prints the last key from the JSON.
Here is the js:
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson, function(data) {
jQuery.each(data, function(i, items) {
jQuery("#fetchmember").html("<li>"+items.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael English","first_name":"Michael","last_name":"English"},
{"id":"100000251643877","name":"Bill Gaither","first_name":"Bill","last_name":"Gaither"}]
I want to print all of name from the json, but it print only last name key of the json. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You're erasing the content on each iteration. Use append instead of html
Instead of
jQuery("#fetchmember").html("<li>"+items.name+"</li>");
Use
jQuery("#fetchmember").append("<li>"+items.name+"</li>");
At iteration, you overwrite the content with last one.
Better to use .append instead of .html, but you have to make the area empty before : jQuery("#fetchmember").empty();

jQuery get href initial value once before it changes

In my application I have an ajax call, and on success it appends some data to an existing links href.
This works great. The issue is, If I want to run the ajax call again and on success, append some different data, it is taking the href value + the new value from the previous ajax call, and than adding the new data after that.
I want it to add the data to the inital href value, before it was appended.
Below is my code:
(I have the sample sample value being appended each time for testing purposes)
//get next page link value, so we can add filter to url
var next_link = $("a.next").attr("href");
$.ajax({
type: "POST",
url: "ajax_calls.php",
data: "instrument="+selected.val()+"&filter=true",
success: function(listing){$("#listings").html(listing);
$("a.next").attr("href", next_link + '&field=x');
},
error: function(){alert(3);$("#error").text("Could not retrieve posts").fadeIn(300).delay(900).fadeOut(300)}
});
Any help on this would be appreciated.
Thank you
How about using jQuery's .data method?
$('#change').click(function(){
var newData = Math.random() * 1000; // fake new data
$('a').each(function(i,e){
var oldHref = $(this).data('oldHref');
if (!oldHref){
var oldHref = $(this).attr('href');
$(this).data('oldHref',oldHref);
}
$(this).attr('href',oldHref + '#' + newData);
});
});
Hello, world!<br />
<input type="button" id="change" value="Change HREF" />
example
Store the old value in a data element, then reference before each new change.

Categories