How to check if a select already has an option selected?

Asked

Viewed 549 times

0

I have a page where there are some selects (representing the functions of users, in which they can be: Leader, Participant or For Knowledge).

There are some business rules:

1- If the user is selected as LEADER, he can no longer have any other function, should only have a (Leader);

2 - Shall not contain more than one leader. For example, I have a list with 3 users and select one of them as LEADER, in the other selects the LEADER option should be disabled, because only a single user is allowed to be the Leader;

I already managed to do this validation in the existing selects on the page, but has the option to add more users in the list. And that’s where my validation doesn’t work, because if I’m already with a user LEADER (selected) and want to add another user in my list, the select of this new user (which is added dynamically via JS) should already come with the option LEADER disabled, because on my list (before adding this new user) there was already a Leader user.

How to check the selected options, so that the validation works also on new users that are added dynamically?

Example: http://jsfiddle.net/andrealbson/4a0r6cwb/

Here’s an example of my JS code that adds dynamic select: inserir a descrição da imagem aqui

  • Hello, Could show how you are doing?

  • André, how are you adding this new select? Are you cloning or adding a string html?

  • It’s by string, @Sergio

  • You can add to the question the code that inserts that new select?

  • I edited the question by adding the image of how I’m doing to add the new select, @Sergio

  • I believe I would only need to create a method that would check the selected options, and if Leader is already selected in some select, the new select would be added and automatically its Leader option would be disabled... But I don’t know how to do it.

Show 1 more comment

1 answer

1

Just execute

   $('select').change();

after you finish adding the new select.

forcing it to perform a change and thus calling every flow of verification

  • Thanks for the tip. I tried it differently: https://jsfiddle.net/andrealbson/5t8noxne/2/ Now I only needed it to disable only when the Leader is selected, and not in the other two options (Participant and For Knowledge)... you can help me?

Browser other questions tagged

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