How to create field dynamically with jQuery? [duplicate]

1

I have a function that I need to validate what the user typed, if it is true enable datepicker . But the way I did it is falling into the method POST of asp.net mvc . Is there a way to create a textbox dynamically with jQuery ?

My code:

View:

<script>
$(document).ready(function () {
    var senha = $('txtSenha').val();

    $("#lblSenha").hide();
    $('#txtNovaDtVenc').click(function () { <-- Aqui é o Datepicker
        $("#lblSenha").toggle();
        $('#btnOK').click(function () {
            if (senha == "administrador") {
                $("#txtNovaDtVenc").datepicker(
                    "option", "disabled", false);
            }
        });
    });
});

</script>

<div id="lblSenha" style="width:300px">
    <table>
        <tr>
            <td>
                Senha: 
            </td>
            <td>
                @Html.TextBox("txtSenha", "", new { @class = "form-control form-control-custom", style="width:100px" })
            </td>
            <td>
                <input type="submit" id="btnOk" class="" value="Ok" onclick=""/>
            </td>
        </tr>
    </table>
</div>
    
asked by anonymous 28.08.2015 / 19:13

2 answers

1

Simple example, where input of type text is added to body

    $('<input>').attr({
        type: 'text',
        name: 'nome_do_campo',
        value: 'teste valor'
    }).appendTo('body');

If you want to add a specific element, just specify it in the appendTo() method.

<form id="frm"></form>

$('<input>').attr({
    type: 'text',
    name: 'nome_do_campo',
    value: 'teste valor'
}).appendTo('#frm');
    
28.08.2015 / 19:20
1

Here's a ready-made example of jsFiddle:

link

$(document).ready(function(){
     var counter = 2;
		
    $("#addButton").click(function () {
				
	if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
	}   
		
	var newTextBoxDiv = $(document.createElement('div'))
	     .attr("id", 'TextBoxDiv' + counter);
                
	newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' 			 + '<input type="text" name="textbox' + counter + 
	      '" id="idCampo' + counter + '" value="" >');
            
	newTextBoxDiv.appendTo("#TextBoxesGroup");

				
	counter++;
     });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><divid='TextBoxesGroup'><divid="TextBoxDiv1">
		<label>Textbox #1 : </label><input type='textbox' id='textbox1'>
	</div>
</div>
    
<input type='button' value='Add TextBox' id='addButton'>
    
28.08.2015 / 19:31