0

When a user doesn't fill the form completely. I want the unfilled input part to return as an empty string.

document.getElementById("skill2").defaultValue = '';

I tried using the above statement but the error comes up as

Cannot assign default value to null

If the form element isn't filled, I get the output as undefined.

I'm attaching a part of the code.

var experiment1 = function()                           
{
var skill2 = $("#skill2").val();
  var html1='<p>'+skill2+'</p>';
  return html1;
 }

$("#bodytag").html(experiment1);

and Yeah, I'm using dynamically generating the form elements. I'm attaching a snippet of that code.

var count2 = 1;
var limit2 = 6;
function addInput2(divName){
     if (count2 == limit2)  {
          alert("You have reached the limit of adding " + count2 + " skills");
     }
     else {
          var newdiv = document.createElement('div');

          newdiv.innerHTML = "<input type='text' name='myInputs[]' id='skill"+(count2+1)+"' style='width:100%;' value=' '  class='text-center' "+ 
          "placeholder='skill"+(count2+1)+"'><br/><br/>";
         
          document.getElementById(divName).appendChild(newdiv);
         
          count2++;
     }
}

So, the problem is, unless the user generates the element, in the output, the value will come as undefined.

  • 2
    no element has `id="skill2"` – Ven Sep 01 '16 at 12:03
  • Yeah. In the main html page. I've created a form and one of the form inputs has an id ="skill2". I need it to pass html values. – flatbreadcandycane Sep 01 '16 at 12:05
  • not at the point your js is executed, no. – Ven Sep 01 '16 at 12:05
  • @JaromandaX I think experiment1 is executing. I checked in this [**LINK**](https://jsfiddle.net/fn69ps7g/) – brk Sep 01 '16 at 12:09
  • It's not, it's never called from anywhere. – roberrrt-s Sep 01 '16 at 12:11
  • @JaromandaX Right. `html` accept function too. _I forgot_ – Tushar Sep 01 '16 at 12:12
  • My main html page's body tag's id is "bodytag". I'm just trying to pass this html variable in the js file there – flatbreadcandycane Sep 01 '16 at 12:12
  • 1
    What you want is default behaviour, no fancy js needed. Unfilled inputs are returned to the backend as empty strings. See for yourself: http://phpfiddle.org/main/code/nk6m-4wfq – Pevara Sep 01 '16 at 12:14
  • Possible Duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Tushar Sep 01 '16 at 12:14
  • The issue is that the form elements are generated dynamically. Maybe, is there a way to add them to the html1 variable only if they are generated and if not generated then take no action. – flatbreadcandycane Sep 01 '16 at 12:40

0 Answers0