Capture field value by its ID and transform into a [duplicate]

0

I want to get the value of a field from my table and turn it into a variable.

Example:

<td id='exemplo'>VALOR EXEMPLO</td>

I want to get the content and turn it into a variable using javascript, I believe it's easy but I do not understand much programming

I tried this way but I could not:

<script type="text/javascript">
var teste = $("#exemplo").val()
</script>

and to call her in php:

<?php

$variavelphp = "<script>document.write(teste)</script>";

echo "$variavelphp"
?>
    
asked by anonymous 26.04.2016 / 07:05

2 answers

0

Change your line of code js to the following:

var teste = $("#exemplo").html();

It would look like this:

var teste = $("#exemplo").html();
alert(teste);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><tdid='exemplo'>VALOREXEMPLO1</td><tdid='exemplo1'>VALOR2</td></tr></table>

First,theeventcallofJQuery$("#exemplo").val() refers to the value attribute of some element, where the element values are usually stored, but its element in fact is td ( structure of the body of a table) which, after all, does not have a value native attribute, to get its value, semantically correct would be to put another element inside it, for example a span or a label which would look something like this: <td><label id='exemplo' value='VALOR EXEMPLO 1'>VALOR EXEMPLO 1</label></td> , so your command line JQuery would not even need to be changed. But this goes according to each one ...

By designing as you wish, the td element only "writes" on the screen what is contained in it, ie the td element type does not natively have the value attribute. To get the content / value contained within a td , you should use the event JavaScript innerHTML(); which in JQuery is equivalent to the HTML(); event

    
26.04.2016 / 07:25
0

If you want to get the content of an element in JS, this is enough:

var teste = document.getElementById('exemplo').innerText;

But it will not work with a single td , without the table structure.

See a working example:

var teste = document.getElementById('exemplo').innerText;

//So para demonstrar:
document.body.innerHTML += 'O valor é ' + teste;
<div id="exemplo">VALOR EXEMPLO</div>

In this case, I used a div to avoid the mentioned problem with td off.

The innerText was used, which is preferable to get the textual content. If you want to get something that contains child elements, give preference to innerHTML .


If your question is about PHP variables, then the subject changes, and it's worth a read about it:

  

Match php variable to a javascript variable

    
26.04.2016 / 08:11