简体   繁体   中英

Without using a form, how can I check an input field is not empty before running function?

I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):

<div id="formBox">
 Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label>&nbsp;<input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
 </div>

Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.

It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.

I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...

    function changeText2(){
    var userInput = document.getElementById('userInput').value;
  $('#formBox input[type="text"]').on('change', function() {
  var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
  alert(linktest);
  });

    var lnk = document.getElementById('lnk');
    lnk.href = "http://www.google.com?q=" + userInput;
    lnk.innerHTML = lnk.href;
}

I tried to check the input box like this, but it didn't work:

 if( $('#formBox input[type="text"]').val== "") {    
   alert('no info');
}

It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,

For Jquery:

if( $('#userInput').val() === "") {    
   alert('no info');
}

For javascript:

if(document.getElementById("userInput").value === "") {    
   alert('no info');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM