Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery encoding for special characters when using val()

Tags:

I have a problem with special characters like &, ä, etc. and their corresponding HTML encoded writing like &, ä etc.

  • When they are used in the value tag of input fields, the browser decodes it automatically, no problem at all.

  • When using jQuerys val() function, the browser has no chance to evaluate the content correctly

    $("button").click(function(){     $("#test").val("&"); }); 

Any idea?

like image 291
1jr Avatar asked Oct 17 '11 10:10

1jr


People also ask

What does VAL () return in jQuery?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

What is $( This val () in jQuery?

The val() method is an inbuilt method in jQuery which is used to returns or set the value of attribute for the selected elements. This method apply on the HTML form elements. Syntax: There are three ways to use this method which are given below: $(selector).val()

What does VAL () do?

val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined . When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .


2 Answers

You can use this age-old entity decoding trick:

$("button").click(function(){     $("#test").val($("<div>").html("&amp;").text()); }); 

Working demo: http://jsfiddle.net/AndyE/XegGy/

It creates a temporary <div> element, sets its HTML to &amp; and then gets the text value, which will be &.

like image 155
Andy E Avatar answered Sep 25 '22 12:09

Andy E


Try .html() function:

$("#test").html("&amp;"); 
like image 20
Pranay Rana Avatar answered Sep 25 '22 12:09

Pranay Rana