Jquery / javascript add text to input field

I have an input field using html5 placeholder:

<input type="text" name="website" class="url" required placeholder="enter website"> 

Using jQuery or direct javascript, I would like to add a string to the data entered by the user in focus. If the field contains more data than the specified string variable (for example: http://example.com ), then the field satisfies my requirements. If it contains only the source string ('http: //'), clear the input value and show the placeholder.

The following code works for me.

 var input = $("#processor .url"); var prefix = 'http://'; input.focus(function() { if (input.val().indexOf(prefix) == -1) { input.val(prefix + input.val()); } }).blur(function() { if (input.val() == prefix) { input.val(''); } }); 

Is there a better way to write this for performance, etc., is this my real question?

+4
source share
1 answer

It is easier than it actually seems. I made a demo based on @Tahir Yasin's comment.

CSS

 .grey { color:#aaa; } 

HTML:

 <input type="text" /> 

JQuery

 var inputval = ""; $(document).ready(function() { // Define your default value to show on input $("input[type='text']").val("Enter your link here..."); // Add grey color or optionally blur effect $("input[type='text']").addClass('grey'); // Save your default value inputval = $("input[type='text']").val(); $("input[type='text']").focusin(function() { // if textbox is empty or got the default value if ($(this).val() == "" || $(this).val() == inputval) { // Clear the box $(this).val("http://"); // Your text here.. // Remove grey color $(this).removeClass('grey'); } }).focusout(function() { // if textbox is empty or just contains your value if ($(this).val() == "" || $(this).val() == "http://" ) { // Put your Default value back $(this).val(inputval); // Add grey color $(this).addClass('grey'); } }); }); 

script: http://jsfiddle.net/BerkerYuceer/TgZ8L/

I just enjoy using jQuery on everystep actions. But since you can see that my code is less than yours, so you are already using the most efficient way.

here is a demo based on your code: http://jsfiddle.net/BerkerYuceer/qbLyD/

you can see the difference yourself, almost the same, but obviously your code is faster.

-1
source

Source: https://habr.com/ru/post/1447398/


All Articles