Javascript or jquery change fields value by name - javascript

I use these codes to change the value of a field. Only the first two lines run, I tried the rest of the code but it did not work and sometimes the message "Uncaught ReferenceError: $ is not defined" is displayed on the console.
document.getElementsByName('tmcp_textfield_6').value = Pak;
document.getElementById("tmcp_textfield_116202d52cbd078").value = Pak;
$("input[name='tmcp_textfield_6']").val(Pak);
document.getElementsByName("tmcp_textfield_6").value = 100;
document.getElementByname("tmcp_textfield_6").value = "100";
$("input[name='tmcp_textfield_6']").val(Pak);

Find the Working Script here, I think you should switch quotes, where double quotes use single, and where single quotes, use double.
var Pak = "Test"
$('input[name="tmcp_textfield_6"]').val(Pak)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tmcp_textfield_6">
Be sure you've also included the jquery file to whatever page you need it to work on

Related

how to console.log html tag attribute's value with hyphen in the middle in JavaScript?

I would need some help about this attribute:
<script id="mysdk" src="https://www.myscript.com/sdk/js?currency=EUR" this-client-token="nsiYXV0aG9yaXphdGlvbkZpbmdlcnByaW50IjoiZGUyYjM4N2FiZWV"></script>
What I'm trying to do is to console.log this-client-token in this way:
var el = document.getElementById("mysdk");
console.log(el.this-client-token);
This because, after making this work, I will be finally able to change the value of this-client-token, since that is my purpose. But I get the following error in the console:
Uncaught ReferenceError: client is not defined
I have no idea why I get this error, is it because of the hyphen? any suggestion?
Thank you!
Elliot
It doesn't work because - is subtraction. It's trying to calculate el.this - client - token, which fails because none of these variables exist.
Change to a data-XXX attribute, and use the dataset property.
var el = document.getElementById("mysdk");
console.log(el.dataset.clientToken);
<script id="mysdk" src="https://www.myscript.com/sdk/js?currency=EUR" data-client-token="nsiYXV0aG9yaXphdGlvbkZpbmdlcnByaW50IjoiZGUyYjM4N2FiZWV"></script>
If you can't change the attribute (because it's required by the SDK script, which you can't change) you can use el.getAttribute("this-client-token")

set value of input with php variable

Im trying to do something really simple I know I should probably be using ajax but I'm just doing some quick tests.
so I have a display.php file with some variable and I want to display the PHP variable in the input text by using document.getElementbyID.value = myVariable
//PHP
<?php
$name = 'Patrick';
?>
//HTML
First Name: <input type="text" id = "fname" name="fname" value="" >
//JS
<script type="text/javascript">
var f = <?php echo($name); ?>;
document.getElementById("fname").value = f;`
</script>
I keep getting the error Uncaught ReferenceError: Patrick is not defined
Not really sure whats wrong with my code it looks pretty simple but it don't want to put the value "Patrick" in the input box.
Tried different ways of writing it with '' or using json_encode but didnt change anything still getting same error.
Uncaught ReferenceError: Patrick is not defined
That's because the resulting javascript is:
var f = Patrick;
Which means set f to the contents of the variable Patrick.
Since there is no variable defined that is named Patrick you'll get the uncaught reference error.
You need to put Patrick in quotes like so:
var f = "Patrick"; // <-- Note the "
Note, since you want to pass data from PHP to JavaScript, a better way would be to use JSON like this:
var f = <?php echo json_encode((string)$data); ?>;
This allows you to pass more complex types of data¹ AND you'll get proper escaped strings.
Proper escaped strings? If the user input is Test " (note the double quote) a primitive approach will break because the resulting javascript will be:
var f = "Test "";
This is not only a bug, but a security issue since user input could contain arbitrary javascript that would get executed.
¹ just remove the (string) cast.

assigning php return value to a javascript variable

I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;

saving value from form doesn't work

So, storing a Java String into a form hidden input value. I call said value via javascript and attempt to store it into a var. Strangely, I can display the value via alert but javascript crashes when I try to save it into a var.
The first line is from the initializing jsp file. It does some stuff that gets the string. The string is a list of ints that I plan on splitting in javascript for some stuff.
"<form id = \"listArrForm\"> <input id = \"listArr\" value = "+ output +" type = \"hidden\"></form>"
var listArr = document.getElementById("listArr").value; //Does work
alert(document.getElementById("listArr").value); //Does work
So yea, I'm guessing it has to do with the the type of value being retrieved?
Well, both should work as you can see in this jsfiddle: http://jsfiddle.net/2eWja/
What are you storing in the value that makes the script not work? Are you sure you're not putting quotes in?
what browser are you using? There could be problem for some
Btw using getElementById is known to be wrong. ;)

Rotator stops working when using replace

I have a problem with our website. I am trying to replace all occurrences of one phone number with different one.
If you go to www.paintballgames.co.uk you will see the regular page
If you go to www.paintballgames.co.uk/?test=phtest you will see one with changed number
However the rotator is not working in the second case.
I tried to compare source codes and only difference was, that in second case, I had some code that is changing the code displayed.
The code I am using is:
<script type="text/javascript">
var str = document.getElementById('forChange').innerHTML;
str = str.replace("844 477 5050", "844 477 5178");
document.getElementById('forChange').innerHTML = str;
</script>
Anyone can share any light on that?
First of all I see an exception with javascript even on the regular site:
$("#container-inline").html("<input type="image" name="op" value="GO" id="search-form-submit" class="form-image" />");
This will not work, as you should either escape quotes or use single quotes:
$("#container-inline").html("<input type=\"image\" name=\"op\" value=\"GO\" id=\"search-form-submit\" class=\"form-image\" />");
or
$("#container-inline").html("<input type='image' name='op' value='GO' id='search-form-submit' class='form-image' />");
UPDATE:
And one more exception in "click_heatmap.js":
Drupal.behaviors.click_heatmap = function()) {
// the "function()) {" is invalid. It should be "function() {"
click_heatmap.js:6 Uncaught SyntaxError: Unexpected token )
if (window.location.href != parent.location.href) {
$('#admin-menu').remove();
}
}
UPDATE 2:
It is possible, that after fixing the errors, you'll see the root of the problem.
UPDATE 3:
Why at all you are changing the phone number in Javascript and not on your server side?
UPDATE 4:
Now I've got even more interesting things! The 'forChange' element is almost the whole site wrapper! You should never write such code!
Instead of that you should have done this:
$(document).ready(function() {
$("SPAN.phone-now").text("your text");
});
UPDATE 5:
Now I can explain, why Javascript stops working. When you write something like body.innerHtml = body.innerHtml.replace(...) ALL the Javascript, which was there gets lost and the new one is not executed. So, nothing works! All references, which were saved in Javascript they point to not visible "old" elements.

Categories