0

i was trying to create validation if user leaves empty prompt it gives error but as i click continue with filling it doesn't show it.

here is my jquery code.

$("#b1").click(function(){
            var pr=prompt("enter new link address");
            $("a").attr("href",pr);

            if($("pr").val() == '')
                {
                    var con1=confirm('Input can not be left blank');
                    if(con1==true)
                    {
                        var pr=prompt("enter new link address");
                        $("a").attr("href",pr);

                    }
                    else{
                        var conn=confirm('Input can not be blank'); 
                    }

                }

            });

here is my html.

<a href="https://www.google.com">google</a>
<button id="b1">attribute(a)</button>

is anyone had idea how to do in correct way to complete my assign.Thanks for your time.

Osama Ijaz
  • 13
  • 3

1 Answers1

1

The issue is because the pr variable holds a string. You're attempting to use a jQuery selector to retrieve that variable and read it's value. You don't need to do that at all, you can just read the value directly.

Also note that I'd suggest you use trim() on the user input to check that the user didn't just hit space a few times. You can also use the con1 value without the boolean equality check.

Finally, note that you can re-organise the logic to make the flow circular (ie. if the user input is empty and they click 'ok' to the message you can start the process again). You can do this by putting the prompt() logic in its own function which is called again when required. Try this:

$("#b1").click(requestLink);

function requestLink() {
  var pr = prompt("enter new link address") || '';
  $("a").attr("href", pr);

  if (pr.trim() === '') {
    var con1 = confirm('Input can not be left blank');
    con1 && requestLink();
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://www.google.com">google</a>
<button id="b1">attribute(a)</button>

One last thing; as you're expecting the user to type a URL and are putting that straight in the DOM I'd strongly suggest you validate that what was entered was in fact a URL. You can do that by following the instructions on this question.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339