Go to the first option after clicking the button

Asked

Viewed 1,981 times

0

I have the following HTML:

<select class="estados" name="estado">
    <option class="op1" value="">1</option>
    <option class="op2" value="">1</option>
    <option class="op3" value="">1</option>
</select>
<input type="reset" class="bt" value="refazer"/>

Let’s say I selected the 3 option op3, when I click the input class="bt" I want him to leave marked the first option op1.

I have to use the Selected jquery?

4 answers

3


If you already know the value, you can set it directly by val().

$("input.bt").on("click", function () {
    // no seu exemplo você não colocou nenhum value
    // nas options, mas aqui iria o value desejado
    $("select[name=estado]").val("valorNaOpcao1");
});

If you always want to select the first one, it can be like this.

$("input.bt").on("click", function () {
    var $select = $("select[name=estado]");
    var $firstOption = $select.find("option:first-child");
    $select.val($firstOption.val());
});

or

$("input.bt").on("click", function () {
    $("select[name=estado]").val($("select[name=estado] option:first-child").val());
});

1

You can use the methods attr and removeAttr.

That way:

$(".bt").click = function () {
  $(".op1").attr("selected", "selected");
  $(".op2").removeAttr("selected");
  $(".op3").removeAttr("selected");
};

And to help differentiate the selected option, do so:

<select class="estados" name="estado">
  <option class="op1" value="">1</option>
  <option class="op2" value="">2</option> <- Alteração do valor dentro da tag
  <option class="op3" value="">3</option> <- Alteração do valor dentro da tag
</select>
  • ah understood, what happens is that the others options will be manageable, forgot to mention this

  • What do you mean? I don’t understand...

1

Just use the function prop() to set the option as marked by clicking the button.

$(".bt").click(function() {
  $(".op1").prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="estados" name="estado">
    <option class="op1" value="">1</option>
    <option class="op2" value="">2</option>
    <option class="op3" value="">3</option>
</select>
<input type="reset" class="bt" value="refazer"/>

1

If you want to do a "reset", ie back to the initial value you can do so:

jsFiddle: http://jsfiddle.net/suhjnxaj/

$(".bt").on("click", function () {
    $("select.estados option").prop('selected', function() {
        return this.defaultSelected;
    });
});

If you want to force the first you can only do so:

jsFiddle: http://jsfiddle.net/suhjnxaj/1/

$(".bt").on("click", function () {
  $("select.estados option").each(function(i){
      $(this).removeAttr("selected");
      if (i == 0) this.selected = true; // onde o "i" é o index desse select, começando em zero
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.