0

I need to add a hidden form element (as part of a large form) which needs to be created and added dynamically. A snippet of what I have so far is:

var value = '*****';
var inputHidden = $('<input>').attr('type', 'hidden')).addClass("warningOnly").val(value);
// conditionally disable new element here
$(elem).append(inputHidden);

This works as expected. What I also want to do is conditionally disable the hidden input before adding it to the form. What I have tried are variants of:

$(inputHidden).prop('disabled', true);

This does not disable the element and I need a way of doing this.

4
  • What benefit is there in disabling a hidden input? What are you trying to accomplish with hidden input? Commented Jan 25, 2018 at 21:18
  • check your .attr('type', hidden)) -- you double-close the end parenthesis. Shouldn't matter, but its a thing. Commented Jan 25, 2018 at 21:19
  • a disabled hidden input won't be sent to the backend with the form submit. for example. Commented Jan 25, 2018 at 21:19
  • As I said, part of a larger form and the point is to stop the submit of the element if other conditions are met. Commented Jan 25, 2018 at 21:29

2 Answers 2

3

Works fine, or as a fiddle:

$(function(){
  var value = '*****';
  var elem = $(".foo");
  var inputHidden = $('<input>')
        .attr('type', 'hidden')
        .addClass("warningOnly")
        .val(value);
  // conditionally disable new element here
  elem.append(inputHidden);

  inputHidden.prop("disabled", true);
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="foo">
Your hidden el will go here. Check the console to see that its disabled. 

</form>

Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried it by disabling the input via the attr, not via the prop? Something like this:

$('#test1').attr('disabled', true);

Comments

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.