Reputation: 2323
I'm adding dynamic input fields to a web form. I'm validating these using this Jquery Mask plugin.
It works fine on the initial input, but not the ones added dynamically.
My input HTML is;
<input type="text" id="mac_address" name="MacAddress[]">
My button HTML is;
<button class="add-mac" type="button" title="Add">Add</button>
The syntax used to validate the input is (works on first input only);
$('#mac_address').mask('ZZ-ZZ-ZZ-ZZ-ZZ-ZZ', {
translation: {
'Z': {
pattern: /[A-Fa-f0-9]/,
optional: false,
}
}
});
How can I add this validation to the dynamic inputs?
I have tried adding the code to a each
loop although it doesn't work.
$('.add-mac').click(function() {
$('#mac_address').each(function() {
$(this).mask('ZZ-ZZ-ZZ-ZZ-ZZ-ZZ', {
translation: {
'Z': {
pattern: /[A-Fa-f0-9]/,
optional: false,
}
}
});
});
});
Any advice is appreciated.
Upvotes: 0
Views: 89
Reputation: 123
Added class to input
<input type="text" class="mac_address" id="mac_address" name="MacAddress[]">
<button class="add-mac" type="button" title="Add">Add</button>
<script>
var count = 1;
$('.add-mac').click(function() {
$('.mac_address').last().clone().attr('id', 'mac_address' + count).val('').insertBefore($(this));
count ++;
});
$(document).on('keyup', '.mac_address', function(){
$('.mac_address').mask('ZZ-ZZ-ZZ-ZZ-ZZ-ZZ', {
translation: {
'Z': {
pattern: /[A-Fa-f0-9]/,
optional: false,
}
}
});
})
$('.mac_address').mask('ZZ-ZZ-ZZ-ZZ-ZZ-ZZ', {
translation: {
'Z': {
pattern: /[A-Fa-f0-9]/,
optional: false,
}
}
});
</script>
https://codepen.io/vommbat/pen/MBXeoj
Upvotes: 1
Reputation: 582
change the id to class
<input type="text" class="mac_address" name="MacAddress[]">
<button class="add-mac" type="button" title="Add">Add</button>
<script>
$('.add-mac').click(function() {
$('.mac_address').each(function() {
$(this).mask('ZZ-ZZ-ZZ-ZZ-ZZ-ZZ', {
translation: {
'Z': {
pattern: /[A-Fa-f0-9]/,
optional: false,
}
}
});
});
});
</script>
Upvotes: 0