I have multiple forms on the same page, at this moment I'm sending its content to another server using jQUery ajax, I'm using individual unique selectors to get their values before send. I want to change the approach in order to reduce the code:
Instead of using individual unique selectors like:
$(#form-1 button).click(function(){
var name = $("[name='name-1']").val();
});
To something like this:
$(form button).click(function(){
var name = $(this).sibbling("[name='name']").val();
});
$("#form-1 button").click(function(){
var name = $("[name='name']").val();
var phone = $("[name='phone']").val();
console.log(name);
console.log(phone);
// [...] ajax stuff
});
$("#form-2 button").click(function(){
var name = $("[name='name-2']").val();
var phone = $("[name='phone-2']").val();
console.log(name);
console.log(phone);
// [...] ajax stuff
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form-1">
<div class="form-group">
<label for="name">Name*</label>
<input type="text" placeholder="Your name" class="form-control" name="name">
</div>
<div class="form-group">
<label for="phone">Name*</label>
<input type="text" placeholder="Your name" class="form-control" name="phone">
</div>
<button type="button">Send </button>
</form>
<form id="form-2">
<div class="form-group">
<label for="nombre">Name*</label>
<input type="text" placeholder="Your name" class="form-control" name="name-2">
</div>
<div class="form-group">
<label for="phone-2">Name*</label>
<input type="text" placeholder="Your name" class="form-control" name="phone-2">
</div>
<button type="button">Send </button>
</form>
All of my forms have the same 3 values (name, email, and phone ).