1

I need to set values for all inputs with ids like re_widget[num][widget_id] . Now I have something like this:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var result = /^\d{1,2}$/;
$('input[id="re_widget[+result+][widget_id]"]').val("my_value");
});
});
</script>
</head>
<body>
<p>Name: <input id="re_widget[1][widget_id]" type="text" name="user1"></p>
<p>Name: <input id="re_widget[2][widget_id]" type="text" name="user2"></p>
<p>Name: <input id="re_widget[3][widget_id]" type="text" name="user3"></p>
<button>Set the value of the input field</button>
</body>
</html>
leon
  • 35
  • 5

1 Answers1

1

Special Character

[ is a special character in jquery, to use it as part of the query, you need to put a \ before

The following code will change the input element's values:

function setValue(id, value) {
  $('#re_widget\\[' + id + '\\]\\[widget_id\\]').val(value);
}

$(document).ready(function() {
  $("button").click(function() {
    setValue(1, 'hello');
    setValue(2, 'world');
    setValue(3, 'leon');
  });
});

Online Demo

Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129