Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change input name according to a specific button in JS

I’m trying to create or import some datas

If data exist, I’m displaying the import button and if didn’t exist, displaying the create button.
I’m working with autocomplete (jquery-ui)

So this is my html :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<form id="form_new" action="{{ path('aff_new') }}" method="post" name="aff">
    <!--<input name="affId"  id="aff_qp" type="text" oninput="onInput(this.value)" class="form-control">-->
    <input name="aff[code]" id="aff_qp" type="text" oninput="onInput(this.value)" class="form-control">
                    
    <button id="create" type="submit" >Create</button>-->
    <button id="import" type="submit" style="display: none">Import</button>
            
</form>

And here my js:

$('#aff_qp').autocomplete({
    source: function(request, response) {
        
    $.getJSON("{{ path('aff_json') }}", function(data){
    var datamap = data.map(function(i) {
        return {
        label: i.code,
        value: i.code,
        desc: i.id
    }
    });
    
    var key = request.term;
    
    datamap = datamap.filter(function(i) {
    return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
    });

    displayImport(false)
    response(datamap);
    })
    },
    minLength: 1,
    delay: 50,
select: function( event, ui ) {
    displayImport(true)
}
});
</script>

I just want to know if is it possible to change name attribute of a input text ?
So, if I click on import the name of input will be :

<input  name="aff[code]"

And if I click on create the name of input will be :

<input  name="affId"

Note: I want use only one input and not 2 input with this two differents names

Anybody can help me and say if it’s possible

>Solution :

Yes you can change the value of the name attribute using the attr() method :

$("#btnCreate").click(function(){
  $("#aff_qp").attr("name","affId");
  console.log($("#aff_qp").attr("name"));
});

$("#btnExport").click(function(){
  $("#aff_qp").attr("name","aff[code]");
  console.log($("#aff_qp").attr("name"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="aff_qp" type="text" name="aff[code]" />
<button id="btnCreate">Create</button>
<button id="btnExport">Export</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading