I have the following code, which works fine:
for (var i = 0; i < <?php echo count($set); ?>; i ++){
$('#inc' + i).on('click', function(){
$('#scratchbox').val('test');
});
}
But what I need is this, which isn't working (the only difference is that '#scratchbox' has changed to '#set' + i):
for (var i = 0; i < <?php echo count($set); ?>; i ++){
$('#inc' + i).on('click', function(){
$('#set' + i).val('test');
});
}
Both the #inc divs and #set textboxes are generated by PHP in the same place and at the same time (technically, in this order: #set1, #inc1, #set2, #inc2, etc.). Also, further down I have this, which is able to retrieve the values contained in the #set textboxes just fine when the event handler is a static #submit div:
$('#submit').click(function(){
for (var i = 0; i < <?php echo count($set); ?>; i ++){
sets[i] = $('#set' + i).val();
}
});
What should I change and why?
Why dont add class names to your elements so you can do something like:
$(document).on('click', '.click_element', function() {
var ID = $(this).attr('id');
$('#set' + ID).val('test');
});
and have for loop separate that creates those click elements with the IDs.
Note that this solution is much faster in terms of execution than having to bind click events within a loop.
By the time your click event handler runs, the value if i is set to its maximum value. Create an IIFE in your loop to save the value of i for each iteration of your for loop.
For example:
for (var i = 0; i < <?php echo count($set); ?>; i ++){
(function (inner_i) {
$('#inc' + inner_i).on('click', function(){
$('#set' + inner_i).val('test');
});
})(i);
}
Here's a good read on using an IIFE (Immediately-Invoked-Function-Expression): http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Related
I can't push the value of my array to my php file.
Script:
<script>
$(document).ready(function() {
var item_code = [];
$('#save').click(function() {
var item_name = [];
var item_value = [];
var item_quantity = [];
for (var i = 0; i < item_code.length; i++) {
item_code.push($(this).val());
}
$('.item_name').each(function() {
item_name.push($(this).val());
});
$('.item_value').each(function() {
item_value.push($(this).val());
});
$('.item_quantity').each(function() {
item_quantity.push($(this).val());
});
$.ajax({
url: "insert2.php",
method: "POST",
data: {
item_name: item_name,
item_code: item_code,
item_value: item_value,
item_quantity: item_quantity,
},
success: function(data) {
}
});
</script>
I have a value storing at "item_code" whenever I search the item code on my search bar. And after that, I want to push the value of item_code[] on the insert2.php.
I'm not getting any error, but the system itself is frozen.
I am guessing that "item_code" variable is also declared globally somewhere else in your code, otherwise there would be no point in iterating through it. Try using a different name instead of "item_code" to send it to "insert2.php".
for (var i = 0; i < item_code.length; i++) {
item_code.push($(this).val());
}
You can't push data into the same array that you are looping because you will never reach the end of it, unless the memory limit will tell you otherwise. Declare "item_code_second" and push into that:
$(document).ready(function() {
var item_code_second = [];
and change your loop:
for (var i = 0; i < item_code.length; i++) {
item_code_second.push($(this).val());
}
also you are pushing the same value "$(this).val()" as many times as there are values in item_code, which is not making any sense and the exact same value in name, quantity and value. $(this) represents the button that was pushed, don't forget you are in an on click event.
Using jQuery load html forms dynamically using append function. Here the following code load the page content dynamically based on number times of values on while loop.
Here I have a struggle on load the content with different values.its working with single value of 0 or 1 on var load_with_value=0; but not on both simultaneously i.e. increment the load_with_value++ for again load the page content of HTML forms.
$(document).ready(function(e) {
$("<DIV>").load("<?php echo $url; ?>", function() //url for loading page
{
var n = $('.item').length + 1; //load the html page content
var i = 1; //iteration for number of times load the content
var count = 2; //check the condition
var load_with_value = 0; //load the page content with different values for display different values on html form
while(i<count) { //loop starts
$("#product").append($(this).html());
i++;
load_with_value++;
}
});
});
First of all let's do some proper code formatting and get rid of the incorrect comments:
$(document).ready(function(e) {
$("<DIV>").load("<?php echo $url; ?>", function() {
var n = $('.item').length + 1;
var i = 1;
var count = 2;
var load_with_value = 0;
while(i<count) {
$("#product").append($(this).html());
i++;
load_with_value++;
}
});
});
Now let's take it apart:
If you want to use a temporary element to store the loaded data you need to assign it to a variable, so instead of
$("<DIV>").load("<?php echo $url; ?>", function() {
do
var tempObject = $("<div/>").load("<?php echo $url; ?>", function() {
Afterwards you can append the temporary element to an existing one with $('#someExistingElement').append(tempObject).
If you want to load the content into an existing element you should use it's ID, class or other selector to do this - not $("<div>").. If you want to load it to all div elements (please don't) then it should be $("div").
Next var n = $('.item').length + 1; makes no sense. It is never used in the code.
While cycle in this case is unnecessary. Don't use while cycles if you don't have to. You can use:
for(var i=0; i<count; i++){
//code
}
What is var load_with_value = 0; used for? I can only see you incrementing it with load_with_value++; but you don't use it anywhere..
Finally if you want to load different content based on the incremented variable it should be done outside of the .load function.. For example
$(document).ready(function(){
for(var i=0; i<5; i++){
$('#container-' + i).load('/somecontent-' + i + '.html');
}
});
This loads the content /somecontent-0.html to /somecontent-4.html into container elements with IDs container-0 to container-4 respectively.
I am trying to serialize value of form elements, where my combox is dynamicall added after user click.
I'm getting value from static combobox bt nt from dynamic combobox.
my code:
<script>
//submit data
$(function (a) {
$("form").submit(function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
});
// populate entree item to select menu
function populate() {
// only declare the variables once
var json = <?php echo $json; ?>, obj, option = ' ', i;
for (var i = 0; i < json.length; i++) {
obj = json[i];
option += '<option value="' + obj.id + '">' + $.trim(obj.title) + '</option>';
}
return option;
}
//add more select box when addmore click
$(function (b) {
var i = 0;
$("a#addmore").click(function () {
i++;
$("p#entree").append('<select name="entree' + i + '">' + populate() + '<select><br>');
});
});
</script>
i got the value when i put my form outside the table. I dnt know why table is blocking the process to get value.
Hello im currently writing my own javascript/PHP css editor and i have it explode the file into tags and its all echoed out into separate text areas from a loop, i was wondering if its possible to scan the page with javascript and get all the content from all the text areas and add them into one variable or one text-area, thanks in advance.
Try this:
function getTextAreasText() {
var all = document.getElementsByTagName("textarea");
var values = "";
for(var i=0; i<all.length; i++) {
values += all[i].value;
}
return values;
}
.
.
.
.
var allTexts = getTextAreasText();
Yes,
If you are familiar with jquery, this is really simple. You would do something like:
var compiled_content = '';
$.('.name_of_class_to_extract').each(function() {
compiled_content += $(this).html();
});
This would give you all HTML content from the specified class ('name_of_class_to_extract') in the variable compiled_content. You could then insert this content into another element like:
$('.class_to_inseert').html(compiled_content);
var a = "";
$("textarea").each(function(){
a += $(this).text();
$(this).prepend("<h1>" + "someValue" + "</h1>") //prepend some markup before each textarea
});
a //concatenated data
Yes possible. Edit following lines for yourself
// jquery code
$(function(){
$.ajax({
url : 'get_content_via.php',
type : 'GET',
data : 'maybe_use_filename',
success:function(data){
var splittedData = data.split("your_seperator"); // like explode
for( var i = 0 ; i < splittedData.lenght ; i++){
$('#targetInput').append(splittedData[i]);
}
}
});
});
I have a JavaScript Object with some information in it.
I have 2 options I can think of to create the HTML from this object. I was wondering which one is the correct way of doing things of is this just all preference?
1) Loop through this array with JavaScript and create the HTML with Jquery?
2) Ajax post/get the object to PHP and loop through this object(php array) and create the HMTL that way? Then return a json encoded object back with the HMTL in it and append it to a div?
What I currently Do to build
var OutterDiv = $(document.createElement('div'));
for loop{
OutterDiv.append("<span>SOME INFO</span>");
var InnerDiv = $(document.createElement('div'));
for loop{
InnerDiv.append("<span>SOME INFO</span>");
InnerDiv.append("<span>SOME INFO</span>");
}
OutterDiv.append(InnerDiv);
}
$("#content").append(OutterDiv);
Why don't you loop through the object and create an HTML string from JavaScript? Then insert that string wherever you need it? I believe this is the fastest way you can accomplish what you want do do. The main idea is that concatenating strings is faster than inserting DOM elements, and perhaps faster than the latency caused by an Http request.
** Edit **
Apparantly, IE is slower at string concatenation (big surprise) and using an array is better.
Example :
var html = [];
for (...) {
html.push( <some html content from your object here> );
}
$(selector).html(html.join(''));
// find the elements you need to handle and perform bindings here
// ex: $('#someelment').click(...);
This is probably as fast as you can get.
** Update **
While performing the task of building HTML with JavaScript is still generally faster, after some testing, it seems that concatenating strings, or building arrays are not faster than creating text nodes. The test can be viewed and forked on jsfiddle.net or here it is for archiving pruposes :
function runTest(testFn, duration) {
var endTime = +new Date() + duration;
var runs = 0;
var charCount = 0;
while (+new Date() < endTime) {
charCount += testFn();
++runs;
}
teardown();
//console.log(testFn.title, 'ran', runs, 'times.');
$('#log').append($('<div></div>').text(testFn.title + ' ran ' + runs + ' times (' + (charCount/1000) + ' cps).'));
}
///
function teardown() {
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
}
///
var testData;
var sample, sampleData;
function generateTestData() {
testData = {};
for (var i=0; i < (Math.random() * (sample[1]-sample[0])) + sample[0]; i++) {
testData['item'+i] = randomString();
}
}
function randomString()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789";
for( var i=0; i < (Math.random() * (sampleData[1]-sampleData[0])) + sampleData[0]; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function shuffle(arr) {
var len = arr.length;
var i = len;
while (i--) {
var p = parseInt(Math.random()*len);
var t = arr[i];
arr[i] = arr[p];
arr[p] = t;
}
return arr;
};
///
var $targetDiv = $('#targetDiv');
var targetDiv = document.getElementById('targetDiv');
///
function jq() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
$targetDiv.html(html.join(''));
return count;
}
function inner() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
targetDiv.innerHTML = html.join('');
return count;
}
function dom() {
var root = document.createElement('div');
var node;
var count = 0;
for (var key in testData) {
count += testData[key].length;
node = document.createElement('div');
node.appendChild(document.createTextNode(testData[key]));
root.appendChild(node);
}
targetDiv.appendChild(root);
return count;
}
///
jq.title = 'jQuery .html';
inner.title = 'innerHTML';
dom.title = 'DOM';
///
sample = [10, 100];
sampleData = [100, 1000];
generateTestData();
var duration = 1000;
var testFn = shuffle([jq, inner, dom]);
$.each(testFn, function(k, fn) {
setTimeout(function() { runTest(fn, duration); }, 0);
});
Overall, while each method is more efficient under some conditions (lots of or few data, long or short strings, etc.), the DOM method seems generally faster in all cases.
So, there you have it. Thanks to GGG for the initial test case.
Do it in javascript. If you already have the data in javascript, taking an extra trip to the server to have PHP do it (letting javascript broker that connection) is wasteful. If it was an intensive calculation, it might make sense to let PHP do it because of speed, but otherwise, seems like a waste.
You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.