Home > Net >  Change a button when empty or another value in list with AJAX Select2
Change a button when empty or another value in list with AJAX Select2

Time:04-12

I'm trying to understand who work the AJAX Select2

I have this:

$(document).ready(function() {
    $('.js-example-basic-single').select2();
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<form>
<select  name="state">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
                    <button id="importerAffaire" type="submit" >Importer</button>

</form>

So, What I want, when I put a another value in the list, I want to display another button:

<button id="creerAffaire" type="submit" >Create</button>

And the most important it's to take into account the new value in the list or another way because what I want, it's if the value doesn't exist need to push into database.

So can you explain me the best way ? thank you

CodePudding user response:

If I understand correctly you want to make it possible to add a new entry to the select, and in case a new entry is added, to send it to your backend through AJAX, so you can update your options values in DB. Following select2 documentation: https://select2.org/tagging

$(document).ready(function() {
  $('.js-example-basic-single').select2({
    tags: true,
    createTag: createEntry
  });
  $("form").submit((e) => e.preventDefault())
  $("select").change(handleSubmit)
});

function createEntry(params) {
  const term = $.trim(params.term);

  if (term === '') {
    return null;
  }

  return {
    id: term,
    text: term,
    newTag: true // add additional parameters
  }
}

function handleSubmit(e) {
  console.log("SUBMITTING VALUE", e.target.value)
  // SEND THE SELECTED OPTION TO YOUR BACKEND, THERE YOU PERFORM THE CHECK IF THE SELECTED VALUE IS A NEW VALUE OR NOT
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<form>
  <select  name="state">
    <option value="AL">Alabama</option>
    <option value="WY">Wyoming</option>
  </select>
</form>

  • Related