Dwza
Dwza

Reputation: 6565

jQuerys .val() doesnt set the bootstrap-input-value

I am searching for a while now with no results so I decided to ask you guys. :)

I have some Bootstrap-inputs like:

<input class='form-control' id='start_name' />
<input class='form-control' id='end_name' />

Normaly I would select data like

var myValue = $('#start_name').val();

The Problem I have is, I want to select an element containing a specified string that gets set before like:

$('#start_name').val('foobar');

Obviously .val() not sets the value of the inputfield. I have to extra add a line like

$('#start_name').attr('value', 'foobar');

or combine it like

$('#start_name').val('foobar').attr('value', 'foobar');

The actuall code I want to use to select the relevant element and empty it is:

$("input[value='" + theSpecifiedValue + "']").val('');

(select Input from X inputs that contains the string)

But since I use bootstrap I have to explicit have to set the value with .attr()

Is there some im missing or is this the only way to do it ?

Here is a Fiddle

Upvotes: 1

Views: 1353

Answers (3)

Pavan Kumar Jorrigala
Pavan Kumar Jorrigala

Reputation: 3085

  1. if you use $('#start_name').val('here') and $('#start_name').prop('value','here') is assigning the value to this.value

    $('#start_name').val(); // here

    and to search with value

    $('body input').filter(function() { return this.value == 'here' }).val('gone');
    
  2. $('#start_name').attr('value', 'here1'); is setting the value in this.attributes

    $('#start_name').attr('value'); // here1

    and to search with value

    $("body").find( "input[value='here1']" )
    

Upvotes: 2

Paul
Paul

Reputation: 646

Bit of a roundabout way, but we can do

$($.grep($("body").find("input"),function(e,i){ return e.value === myValue })).val('gone');

jQuery selectors use the literal HTML to select. Setting a value with .val() sets the html object's property "value". It does not set change the literal text in the HTML, which is what jQuery is using with its selector. So instead we grab all inputs and return a list of items where the property "value" matches our search string. Instead of using grep, you could use a for loop, map, etc, and probably make the lookup faster.

Upvotes: 1

vartika
vartika

Reputation: 494

Try

 $(function () {
        $("body").find("input[value='" + theSpecifiedValue + "']").val('');
 });

Upvotes: -1

Related Questions