Home > Blockchain >  How do I reference an html dropdown list via a button function?
How do I reference an html dropdown list via a button function?

Time:03-02

In my Razor page I have this:

<label for="tentacles">Seleccione opción:</label>
        <select name="opciones" id="list">
               <option value="demo">Demo</option>
               <option value="demo2">Demo 2</option>
        </select>
    <button type="submit"  onclick="myFunction()>Conectar</button>

@code {

private void myFunction {

(I need an instance variable here? in that case, how?)

}

As you can see, I have an HTML dropdown list and I intend to make it work with a button event, the question is how do I reference it from that function... I'm new in C#...

I know that in Javascript it's referenced with getElementById, but in this case, how would it be?

Help is appreciated!

CodePudding user response:

It looks you are using blazor,here is a working demo for blazor:

<label for="tentacles">Seleccione opción:</label>
<select name="opciones" id="list" value="@Opciones" @onchange="@((ChangeEventArgs __e) => Opciones = __e?.Value?.ToString())">
    <option value="demo">Demo</option>
    <option value="demo2">Demo 2</option>
</select>
<button type="submit"  @onclick="myFunction">Conectar</button>
@code {
private string Opciones { get; set; }="demo";
private void myFunction() {

(I need an instance variable here? in that case, how?)

}

When select changes value,Opciones value will be changed,and if you want to get select value in myFunction(),you only need to use Opciones.

CodePudding user response:

I do not have full context of what do you want to achieve, but this is how you can get instance of select

<select @ref=@mySelect name="opciones" id="list">
    <option value="demo">Demo</option>
    <option value="demo2">Demo 2</option>
</select>

Then in code behind

@code{
     private ElementReference mySelect;

     private string Opciones { get; set; }="demo";

     private void myFunction() {
        //  here you can get reference for select in mySelect
     }    
}
  • Related