Your code checks if someone presses p
is all.
To do it correctly you need to check contents of input with oninput=yourfunction()
instead.
It would be easier if you gave it an id <input ... id="this_input">
, then you can access it with var v = document.getElementById("this_input").value;
, but you can access it by tag as document.getElementsByTagName("input")[0].value;
where [0] is index of your input on the page.
Then you search for a URL in that string with v.search("[some_regexp]");
, it returns -1 if it doesn't find a URL. So it's if(v.search("...") >= 0) alert("There is a URL in the input somewhere.");
And lastly depending on what you think is a URL the regexp would be different, the most paranoid one would check if there're 2 words separated by a dot.
Here it is: ((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?
It's unnecessarily long, but you can google a shorter one for your exact purpose. For example to find if there's an http somewhere in the string you just do (http)
, which doesn't dtop people from posting links, like www.google.com.
Complete example would be:
<p>Enter http on the keyboard in the input field, to alert some text.</p>
<input type="text" size="50" oninput=check()>
<script>
function check() {
var v = document.getElementsByTagName("input")[0].value;
if(v.search("(http)") >= 0)
alert("woot");
}
</script>