Mohammadov
Mohammadov

Reputation: 613

How to put a javascript variable into view in mvc 4?

I know that is a small problem, but i didn't found any solution, so i have a javascript variable <script> var coords = []; </script> and i want to put it in my view :

<input type="submit" name="Tracking" value="Tracking" data-coords="//here !!!"/>

so please if someone have any idea i will be very appreciate.

Upvotes: 0

Views: 497

Answers (3)

Konrad Gadzina
Konrad Gadzina

Reputation: 3404

If you want to set dynamic values to something in your HTML, you should use JavaScript to do it. The exact way of doing this depends on context - when exactly you want to set those values and what you want to do with them before.

If you want to set value of data-coords on DOM load and you use jQuery, write code that updates data-coords attribute of this input inside $(document).ready function. You can use attr function to do this if you use jQuery.

Upvotes: 1

Ozan &#199;AKİN
Ozan &#199;AKİN

Reputation: 163

Method 1; You Can use this code;

 $("[name='Tracking']").attr("data-coords",coords);

Method 2;

if dont required use data-coords

you can use jquery .data()..

replace this;

<input type="submit" id="Tracking" name="Tracking" value="Tracking"/>

and

$("#Tracking").data("data-coords", coords);

Upvotes: 1

von v.
von v.

Reputation: 17108

You can handle it on the client side:

// javascript version
// safe, if you have only one element that has a name "Tracking"
var btn = document.getElementsByName("Tracking")[0].value;
var a = document.createAttribute('data-coords');
a.value = coords;
btn.setAttributeNode(a);

// or do it easier with jquery
$('[name="Tracking"]').attr('data-coords', coords);

Upvotes: 1

Related Questions