How to create a new img tag with jQuery?

Asked

Viewed 907 times

2

I would like to change the c:\imagem.jpg according to what was selected in the <option id="selecao" value="01">c:\imagem.jpg</option>. Follows the code:

<DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $(function(){
        $("#btnTeste").click(function(){
          var select = document.getElementById("selecao");
          alert(select.innerText);
          var img = $('<img />', { id: 'Myid', src: 'c:\imagem.jpg' , alt:'MyAlt'}) .appendTo($('#divPrincipal'));
        });
    })
    </script>
</head>
<body>
    <div id="divPrincipal">
    </div>
    <select name="select-native-fc" >
        <option id="selecao" value="01">c:\imagem.jpg</option>
    </select>
    <button id="btnTeste">Testar</button>
</body>
</html>

This is the code from Views:

@model ProjetoDelphiMobile.Models.cliente

@{
    ViewBag.Title = "";
}

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

<script>
    $(function () {
        $("#btnTeste").click(function () {
            var src = $('select[name="select-native-fc"]').text();
            alert(src);
            var img = $('<img />', { id: 'Myid', src: src, alt: 'MyAlt' }).appendTo($('#divPrincipal'));
        });
    })
</script>
<form>
    <fieldset data-role="controlgroup">
  @*      <div >
            <img id="foto" src="@Url.Action("Thumbnail", "ConsultaCliente", new {caminhofoto = "caminho", largura = 100, altura = 100 })" alt="thumbnail" />
        </div>*@
            <div id="divPrincipal">
            </div>
               <label>Foto:</label>
               <div  name="select-native-fc" >
                    @Html.DropDownList("idFoto", String.Empty) 
                </div>
              <button id="btnTeste">Testar</button>
        <ul data-role="listview" data-inset="true" data-divider-theme="e">
            <li><a href="/ConsultaCliente">Retornar para consulta</a></li>
        </ul>
    </fieldset>
</form>

This is the Controller code:

    public ActionResult AtualizaCliente(int id)
    {
        ViewBag.idFoto = new SelectList(dao.fotos, "idFoto", "Foto");
        ViewBag.idInformacao = new SelectList(dao.informacoes, "idInformacao", "titulo");
        return View(dao.cliente.Find(id));
    }

1 answer

3

If you want to create a new image using information from select you can do so using the method .text() that gives you the text of selects:

$("#btnTeste").click(function(){
      var src = $('[name="select-native-fc"] option:selected').text();
      alert(src);
      var img = $('<img />', { id: 'Myid', src: src , alt:'MyAlt'}) .appendTo($('#divPrincipal'));
});

I suggest instead of giving each ID’s option that you give your ID to your own select, since Ids have to be unique.

Browser other questions tagged

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