简体   繁体   中英

I have to change the input type to tel from text of the html form on runtime using jquery

I am very new to jQuery. I have HTML form and I want to change the input type from text to tel when user clicks the input box using jquery. Also there would be many field having input type as text(creating aem component) and even the class is name would be same hence, selection of that form element should be pattern="[+0-9()-]*".

<form class="form">
    <input type="text" name="myPassword" pattern="[+0-9()-]*"/>
    <input type="text" name="myPassword" />
</form>
$("button").click(function() {
    $('.form').find(pattern:'[+0-9()-]*').each(function() {
       $("<input type='tel' />").attr({ name: this.name, value: this.value }).insertBefore(this);
    }).remove();
});

The output should be when user just click the input field the input type should be change to "tel".

I'm not sure about my comprehension of your problem but here's a hint on how to do it

$("button").click(function() {
  $('.form').find('[name="myPassword"]').each(function() {
    $(this).attr('type', 'tel');
  });
});

The problem is in the find() part. Here is the right syntax:

$("button").click(function() {
    $(".form").find("input[pattern='[+0-9()-\]*']").each(function() {
       $("<input type='tel' />").attr({ name: this.name, value: this.value }).insertBefore(this);
    }).remove();
});

Now about what you said in your comment, i think it can be done in a much simpler way. Replace the hole thing with a click listener on inputs with the pattern [+0-9()-\]* , and change their type to tel when they are clicked:

$("input[pattern='[+0-9()-\]*']").click(function() {
    $(this).attr("type", "tel");
});

Also, I don't know if you really need to wait for the inputs to be clicked, but if not, you could simply change their types at page load by running this when document is ready:

$("input[pattern='[+0-9()-\]*']").attr("type", "tel");

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