Jquery Wordpress javascript split error inside console - javascript

I do have a problem with my split function, it's throwing a error see image:
error inside console
Hidden Input field inside php file:
<input class="file-id" name="_file-id" type="hidden" value="<?php echo esc_attr($file_ids); ?>" />
I saved already values inside it see image:
values inside hidden input field
Code:
jQuery(function($){
var savedIds = $('.file-id').val();
var savedIdsArr = savedIds.split(',');
for(i = 0; i < savedIdsArr.length; i++) {
savedIdsArr[i] = parseInt(savedIdsArr[i]);
}
console.log(savedIdsArr);
});
img(savedIdsArr)
if i do watch the console my code is working fine but it still's show me the error of the split function.
Hopefully someone can explain it to me and knows the solution.

you cann't use split() over javascript array . Split is a string function.
If you are directly getting ids in savedIds(here), iterate it you will get one by one values as required

Related

Javascript - Use document.getelementbyid().value with a variable

I'm trying to capture the value of a text field on an HTML form using document.getElementById(my_field).value where the variable my_field is passed to my function dynamically, but am hitting a wall.
How do you use a variable in this context?
The function just doesn't seem to parse the contents of the variable my_field, instead treating it as a string no matter whether I use quotes, square brackets or curly braces.
function myFunction() {
var my_field = arguments[0];
var current_value = document.getElementById(my_field).value;
alert ("Current Value: " + current_value);
}
I'm doing it this way because I have multiple records on a form and each row has its own unique id for the required field.
Running the above just does nothing. The alert never pops which I assume is because current_value never gets set.
To add further detail - I tried to simplify everything for the purposes of this question as there's lots of other unnecessary complications that will only detract from the main issue - on my HTML form is a text field which calls my function on onChange
onchange="enforce_multiples('quantity[<?php echo $line_id; ?>]',<?php echo $product['minimum'];?>)"
I've checked that arguments[0] and [1] are being captured correctly by outputting their values to an alert. Everything works fine up until I try to set the quantity_entered value.
<script>
function enforce_multiples() {
var line_id = arguments[0];
var quantity_increments = arguments[1];
var quantity_entered = document.getElementById([line_id]).value;
alert("QE" + quantity_entered);
//var quantity_mod = quantity_entered % quantity_increments;
//var revised_quantity = quantity_entered - quantity_mod;
//alert("RQ: " + revised_quantity);
//document.getElementById([line_id]).value = revised_quantity;
}
</script>
Checked the console and I receive the error: Uncaught TypeError: Cannot read property 'value' of null on the geElementById line
You should write document.getElementById(my_field) instead of document.getelementbyid(my_field).
OK so I got to the bottom of this in case anyone is interested.
In order to use a variable in document.getElementById() you simply add the variable name with no quotes.
var my_variable = "field1";
document.getElementById(my_variable);
The reason this wasn't working on my form was because the text fields only had the name parameter and not an id parameter.
So I needed to change:
<input type="text" name="field_name" value="1234" />
To
<input type="text" name="field_name" id="field_name" value="1234" />
And that sorted it. Otherwise I was just getting generic NULL error messages in the console.

Using jQuery to supply `<option>` elements via multidimensional array to `<datalist>`

I have searched the posts to find a solution to what I would like to do. I want to create a list for <datalist> using a JavaScript array. I found a for loop that worked for someone else, and I modified it slightly to work with a 2D array. I have used the code below on JSFiddle, and it works, but when I include it into my larger code, the <datalist> does now show up even though the code is simply copied and pasted into my larger code.
Also, I'm not sure how to change the code below to jQuery, if you could help with that I would greatly appreciate it as well.
var test = [
['text1',1,2,3,4],
['text2',1,2,3,4],
['text3',1,2,3,4],
['text4',1,2,3,4],
['text5',1,2,3,4],
['text6',1,2,3,4],
['text7',1,2,3,4],
];
var options = '';
for(var i = 0; i < test.length; i++) {
options += '<option value="'+test[i][0]+'" />';
document.getElementById('maltList').innerHTML = options;
}
<input name ="malt" list="maltList"/>
<datalist id="maltList"></datalist>
You can use the jQuery#append method to add a list of options (mapped from the data in your test array using Array#map) to your datalist. Since the code you had before was working as a snippet, though, I'm not sure whether this will actually help you in whatever context it had failed previously.
Let me know if you get any error messages and I will try to help you resolve them.
var test = [
['text1',1,2,3,4],
['text2',1,2,3,4],
['text3',1,2,3,4],
['text4',1,2,3,4],
['text5',1,2,3,4],
['text6',1,2,3,4],
['text7',1,2,3,4],
]
$('#maltList').append(test.map(function (e) {
return new Option(e[0])
}))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name ="malt" list="maltList"/>
<datalist id="maltList"></datalist>

Get javascript function parameters

I am trying to write a code for Greasemonkey. I can handle the tagnames, ids etc. But I got stuck in the 'script' tag. I can get the innerHTML of this script tag. But I want to get the input parameters only of the 'on' function, specifically 4th input which is a number. And store them in an array.
<ol id="online1">
<script language="javascript" >
on('0','2','abc','401757','');
on('1','1','asd','1115337','');
on('2','2','asdsad','1169333','');
gi('asdasd','10453','');
gi('asdasd','10453','');
.
.
.
.
</script>
Should result in
array = [401757,1115337,1169333];
I can get the innerHTML of the script like this:
window.frames[2].document.getElementById('online1').getElementsByTagName('script')[0].innerHTML
As per your example, you can just use .split() on the innerHTML using , as a delimiter. If you want, you can add in an extra safeguard and use a function to detect whether you're getting a number.
JavaScript:
var vals = document.getElementsByTagName('script')[2].innerHTML.split(',');
for(var i = 3; i < vals.length; i+=4)
{
console.log(vals[i]);
}
Output:
'401757'
'1115337'
'1169333'
'10453'
jsFiddle

passing PHP arrays to javascript with JSON

Okay so I know this has been asked before and I've tried the solutions, but for some reason they don't work for me so I'm asking for some help. I haven't used JSON yet so maybe it's something silly but I have no clue...
Here's the code:
<?php
$array;
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<divShow>
</divShow>
<script>
function showArray(){
var array = <?php echo json_encode($array); ?>;
//Failed attempt to display array in the div field show
document.getElementById("divShow").appendChild(array);
//Failed attempt to display the array with an alert.
for(var i=0; i<2; i++){
alert(array[i]);
}
};
</script>
</html>
So what do you guys think? Am I missing something? Is it possible that the array was successfully passed to javascript but for some reason won't show?
Thanks,
-Alex
EDIT:
So I'm getting a series of arrays from a text file. I use these arrays as strings to display on the page and then convert them to float arrays. When I echo one of the float arrays such as $Z_Ausmass with:
echo json_encode($Z_Ausmass);
I get [25.39999961853,121.48651123047]. However, when I use the following to display the array through javascript:
function calc(){
var Z_Ausmass = <?php echo json_encode($Z_Ausmass); ?>;
for(var o=0; o<Z_Ausmass.length; o++){
var textnode = document.createTextNode(Z_Ausmass[o]);
document.getElementById("divCalc").appendChild(textnode);
}
};
it does not work. It's vital I get the float arrays in the script because the script needs to make calculations based on them and then display the calculations to the user.
When i execute the code it works ok.
The first attempt fails because you can't append the complete array. You need to append each element in the array seperately.
The second attempt works correctly. You only need to remove the first attempt to make it work because the first attempt stops the execution of the javascript.
edit
I tried to fix the code for you. I used a simple array with only text.
The element you wanted to show in did not have the id you where referencing to
<divShow></divShow>//wrong
<div id="divShow"></div>//right
to loop trough the complete array you do not want to hard code the max # of elements use arr.length as max for the 'for'-loop.
You can't directly append raw text to an html element. You need to make a TextNode of it and then append that node to the html element.
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
So The working code will be something like this:
<?php
$array = array("test","text","show");
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<div id="divShow">
</div>
<script>
function showArray(){
var arr = <?php echo json_encode($array); ?>;
//Put the text in a text node, append to the div
for(var i=0; i< arr.length; i++){
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
}
};
</script>
</html>

Get the value of a variable who's name matches this string?

I'm a bit new at Javascript... What I need to do is get a variable by it's name, which the code can get as a string, but that string is going to be different depending on input etc. My searching hasn't gotten anything so far, but maybe I don't know the correct terms to use to describe this. This is what I made so far:
var 1name = 'test'; // This part is added by php, and
var 1data = 'THIS IS TEST TABLE RAWR'; // the variable names end up being
var 2name = 'etc'; // a number followed by "name", etc.
var 2data = 'MORE PLACEHOLDER TEXT HERE';
later on:
function editTable(id) {
if (id != null) {
document.getElementById('name').value = window[id + "name"];
}
}
and a button:
<input type='button' value='Edit' onclick="editTable(document.getElementById('table').value)" />
The button grabs the value of a form field, which will match the number of one set of the variables added from the php. How can I get this to work? I've already made sure the variables are getting inserted into the page, and that the button gets a value that matches.
Can you see what I was going for or do you need more explanation?
Variables cannot start with numbers. Personally I think you should use an array like this:
var data = [
{name:"text",data:"THIS IS TEST TABLE RAWR"},
{name:"etc",data:"MORE PLACEHOLDER TEXT HERE"}
];
Since you've mentioned PHP outputting this, look at json_encode. Then you could just have:
var data = <?php echo json_encode($data); ?>;
Assuming, of course, that $data is your array structure.

Categories