1

I was trying to get all the inputs inside my form and fill the text fields with the value that came from the database. I would like to ask if there are other ways to do this because currently I am using nested switch case and it looks awful. So here is my code:

function filled(data){
    modal.find('.form-control, input').each(function(index, el) {
        var element = $(this).attr('name'),
                $this = $(this);

        switch($this.get(0).tagName){
            case "INPUT" :
                var $type = $this.attr('type');
                switch($type){
                    case "radio": case "checkbox":
                        if($this.prop('value') == data[element])
                            $this.prop('checked', true);
                        break;
                    case "text": case "number":
                        $this.val(data[element]);
                        break;
                }
                break;
            case "TEXTAREA" :
                $this.text(data[element]);
                break;
        }
    });
}

1 Answer 1

1

You can try a if...else..if construct with is() like

function filled(data) {
  modal.find('.form-control, input').each(function(index, el) {
    var element = $(this).attr('name'),
      $this = $(this);

    if ($this.is(':radio, :checkbox')) {
      //stuff
    } else if ($this.is(':text, [type="number"]')) {
      //stuff
    } else if ($this.is('textarea')) {
      //stuff
    }
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

how can I determine which :radio should be checked? i have this code $this.prop('value') == data[element] to check if the value is the same..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.