Show fields IF select option is selected - javascript

I'm trying to make my form somehow more user-friendly. So don't show at the first spot all the fields but only the necessary one, and if a user will meet certain criteria, then show the rest of the fields. It's based on newest bootstrap. My codes are like below:
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation');
var showHidden = document.querySelectorAll('.d-none');
var selectGroup = document.getElementById('target-audience');
selectGroup.addEventListener('change', function handleChange(event) {
if (event.target.value === '8') {
showHidden.style.display = 'block!important';
} else {
showHidden.style.display = 'none';
}
});
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#400;700&display=swap');
html, body {
font-family: 'Poppins', sans-serif;
}
#mailchimp-container h1 {
font-size:1em;
text-transform:uppercase;
font-weight:bold;
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container" id="mailchimp-container">
<div class="row">
<div class="col">
<h1 class="py-3">
Form test
</h1>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email" class="col-form-label">Email</label>
<input id="email" name="email" type="email" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="fname" class="col-form-label">Name</label>
<input id="fname" name="fname" type="text" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="target-audience" class="col-form-label">Who are you?</label>
<select id="target-audience" name="target-audience" class="form-select" required>
<option disabled selected value="">--</option>
<option value="8">Fans of cars, motors and bikes</option>
<option value="16">Fans of flowers</option>
<option value="24">Fans of food</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group">
<label for="location" class="col-form-label">Your location</label>
<select id="location" name="location" class="form-select" required>
<option disabled selected value="">--</option>
<option value="europe">Europe</option>
<option value="anz">ANZ</option>
<option value="americas">Americas</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group d-none">
<label for="fav-car" class="col-form-label">Favourite car brand</label>
<input id="fav-car" name="fav-car" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-bike" class="col-form-label">Favourite bike brand</label>
<input id="fav-bike" name="fav-bike" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-motorcycle" class="col-form-label text-start">Favourite motorcycle brand</label>
<input id="fav-motorcycle" name="fav-motorcycle" type="text" class="form-control">
</div>
<div class="form-group py-3">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
While the form is validating properly, unfortunately the javascript that is suppose to show the fields doesn't. In practice when a user will pick value=8 so he will be a fan of cars/bikes/motors, then the fields should appear.
Thank!

showHidden has a 3 nodes. So you need to iterate and for importing implementation you can use setProperty() method like this;
selectGroup.addEventListener('change', function handleChange(event) {
if (event.target.value === '8') {
showHidden.forEach(div => div.style.setProperty('display', 'block', 'important'))
} else {
showHidden.forEach(div => div.style.setProperty('display', 'none', 'important'))
}
});

Loop through showHidden since it's a NodeList, then use setAttribute('style', 'display: block!important') since you can't add important to an HTMLElement:
(function() {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation');
var showHidden = document.querySelectorAll('.d-none');
var selectGroup = document.getElementById('target-audience');
selectGroup.addEventListener('change', function(event) {
if (event.target.value === '8') {
showHidden.forEach(function(el) {
el.setAttribute('style', 'display: block!important');
})
} else {
showHidden.forEach(function(el) {
el.setAttribute('style', 'display: none');
})
}
});
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#400;700&display=swap');
html,
body {
font-family: 'Poppins', sans-serif;
}
#mailchimp-container h1 {
font-size: 1em;
text-transform: uppercase;
font-weight: bold;
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="container" id="mailchimp-container">
<div class="row">
<div class="col">
<h1 class="py-3">
Form test
</h1>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email" class="col-form-label">Email</label>
<input id="email" name="email" type="email" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="fname" class="col-form-label">Name</label>
<input id="fname" name="fname" type="text" class="form-control" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="form-group">
<label for="target-audience" class="col-form-label">Who are you?</label>
<select id="target-audience" name="target-audience" class="form-select" required>
<option disabled selected value="">--</option>
<option value="8">Fans of cars, motors and bikes</option>
<option value="16">Fans of flowers</option>
<option value="24">Fans of food</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group">
<label for="location" class="col-form-label">Your location</label>
<select id="location" name="location" class="form-select" required>
<option disabled selected value="">--</option>
<option value="europe">Europe</option>
<option value="anz">ANZ</option>
<option value="americas">Americas</option>
</select>
<div class="invalid-feedback">
Pick proper option
</div>
</div>
<div class="form-group d-none">
<label for="fav-car" class="col-form-label">Favourite car brand</label>
<input id="fav-car" name="fav-car" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-bike" class="col-form-label">Favourite bike brand</label>
<input id="fav-bike" name="fav-bike" type="text" class="form-control">
</div>
<div class="form-group d-none">
<label for="fav-motorcycle" class="col-form-label text-start">Favourite motorcycle brand</label>
<input id="fav-motorcycle" name="fav-motorcycle" type="text" class="form-control">
</div>
<div class="form-group py-3">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>

Related

How to show-hide div element in JavaScript as per select element value?

Here are options (option 0, option 1 and option 2). If option 1 is selected, the videoShowHide should be shown, and hide the onlineShowHide and handoutShowHide.
HTML:
document.getElementById('type').onchange(function() {
if (document.getElementById('type').value === 0) {
document.getElementById('onlineShowHide').classList.add('d-block');
document.getElementById('handoutShowHide').classList.add('d-none');
document.getElementById('videoShowHide').classList.add('d-none');
}
if (document.getElementById('type').value === 1) {
document.getElementById('onlineShowHide').classList.add('d-none');
document.getElementById('handoutShowHide').classList.add('d-block');
document.getElementById('videoShowHide').classList.add('d-none');
}
if (document.getElementById('type').value === 2) {
document.getElementById('onlineShowHide').classList.add('d-none');
document.getElementById('handoutShowHide').classList.add('d-none');
document.getElementById('videoShowHide').classList.add('d-block');
}
})
<div class="col-lg-6 mb-3">
<label for="type" class="form-label">نوع</label>
<select class="form-select" id="type" name="type">
<option value="0">Online</option>
<option value="1">Video</option>
<option value="2">Handout</option>
</select>
</div>
<div class="col-lg-6 mb-3" id="onlineShowHide">
<label for="online" class="form-label">Online</label>
<input type="text" class="form-control" id="online" name="online">
</div>
<div class="col-lg-6 mb-3 d-none" id="videoShowHide">
<label for="video" class="form-label">Video</label>
<input type="file" class="form-control" id="video" name="video">
</div>
<div class="col-lg-6 mb-3 d-none" id="handoutShowHide">
<label for="handout" class="form-label">Handout</label>
<input type="file" class="form-control" id="handout" name="handout">
</div>
To add an event you can do it using addEventListener or assign a function to this event like this: document.getElementById('type').onchange = function() {}.
When you retrieve the value from the #type element it will be a string and not a number.
You are trying to add d-block to the element to show it but you are not removing the already existing d-none class so you should rather remove the d-none class to show the element.
Example:
let onlineShowHide = document.getElementById('onlineShowHide');
let handoutShowHide = document.getElementById('handoutShowHide');
let videoShowHide = document.getElementById('videoShowHide');
let type = document.getElementById('type');
type.onchange = function () {
onlineShowHide.classList.add('d-none');
videoShowHide.classList.add('d-none');
handoutShowHide.classList.add('d-none');
if(type.value === '0') {
onlineShowHide.classList.remove('d-none');
}
if(type.value === '1') {
videoShowHide.classList.remove('d-none');
}
if(type.value === '2') {
handoutShowHide.classList.remove('d-none');
}
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-lg-6 mb-3">
<label for="type" class="form-label">نوع</label>
<select class="form-select" id="type" name="type">
<option value="0">Online</option>
<option value="1">Video</option>
<option value="2">Handout</option>
</select>
</div>
<div class="col-lg-6 mb-3" id="onlineShowHide">
<label for="online" class="form-label">Online</label>
<input type="text" class="form-control" id="online" name="online">
</div>
<div class="col-lg-6 mb-3 d-none" id="videoShowHide">
<label for="video" class="form-label">Video</label>
<input type="file" class="form-control" id="video" name="video">
</div>
<div class="col-lg-6 mb-3 d-none" id="handoutShowHide">
<label for="handout" class="form-label">Handout</label>
<input type="file" class="form-control" id="handout" name="handout">
</div>

Get textarea value from selected input by data id, from appended (jquery) elements

I was able to get the value for Description (textarea) from the first service (selected input) (which is right), for the attribute of data id, but I'm having a problem getting it from appended elements, after using the add more button
What am I missing, please?
Below is my code and I can explain further if need be.
<div class="service-box">
<div class="row">
<div class="col-md-12 service-group">
<div class="row">
<div class="form-group mb-3 col-md-6">
<label class="form-label">Service</label>
<div >
<select type="text" class="form-select" placeholder="Services" value="" name="service" id="service">
<option value="" disabled selected>Select your option</option>
#foreach ($services as $service)
<option value="{{$service->service_name}}" data-id="{{$service->description}}">{{$service->service_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group mb-3 col-md-6">
<label class="form-label">Amount</label>
<div >
<input type="text" class="form-control" name="amount" id="amount" placeholder="Amount">
</div>
</div>
<div class="form-group mb-3 col-md-12">
<label class="form-label">Description</label>
<textarea class="form-control" id="description" name="description" rows="6" placeholder="Content.." readonly></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" id="addmore" class="btn btn-default">Add more</button>
<button type="button" id="remove" class="btn btn-default">Remove</button>
</div>
$("#addmore").click(function() {
var serviceGroupHTML = $('.service-group').html();
$( ".service-box" ).append(serviceGroupHTML);
});
$("#remove").on("click", function() {
$(".service-box").children().last().remove();
});
<!-- This is where the problem lies -->
const service = new Array(document.getElementById("service"));
const description = new Array(document.getElementById("description"));
service[0].addEventListener("change", function(){
description[0].value = $('#service option:selected').data('id');
})
service[1].addEventListener("change", function(){
description[1].value = $('#service option:selected').data('id');
})
As your newly created element are dynamic so you need to bind it with static element. Then, you can get the value of the data-attribute by using $(this).find("option:selected").data("id") and assign this to your textarea of that particular group .
Demo Code :
$("#addmore").click(function() {
$('.service-group:first').clone().find("input:text,textarea").val("").end()
.appendTo('.service-box');
});
$("#remove").on("click", function() {
$(".service-box").children().last().remove();
});
$("body").on("change", "select[name=service]", function() {
//get description for data-attribute
var description = $(this).find("option:selected").data("id");
//assign value
$(this).closest(".service-group").find("textarea[name=description]").val(description)
})
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="service-box">
<div class="row service-group">
<div class="col-md-12">
<div class="row">
<div class="form-group mb-3 col-md-6">
<label class="form-label">Service</label>
<div>
<select type="text" class="form-select" placeholder="Services" value="" name="service">
<option value="" disabled selected>Select your option</option>
<option value="1" data-id="This test">XYZ</option>
<option value="1" data-id="This test22">Z22</option>
<option value="1" data-id="This test33">YZ33</option>
</select>
</div>
</div>
<div class="form-group mb-3 col-md-6">
<label class="form-label">Amount</label>
<div>
<input type="text" class="form-control" name="amount" id="amount" placeholder="Amount">
</div>
</div>
<div class="form-group mb-3 col-md-12">
<label class="form-label">Description</label>
<textarea class="form-control" name="description" rows="6" placeholder="Content.." readonly></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" id="addmore" class="btn btn-default">Add more</button>
<button type="button" id="remove" class="btn btn-default">Remove</button>
</div>

How to show radio button after selecting option

I have a form with several inputs like below
This is the value from Jenis Layanan
When I choose value from Jenis Layanan, if I choose Corporate, I want to add new field radio button below jenis layanan. And if I choose Perorangan or Home Visit, radio button dissapear.
How can I make it work like this?
My code
<div class="p-2">
<div class="form-group">
<label class="form-label font-weight-bold" for="sub_product">Jenis Layanan</label>
<select class="form-control" name="sub_product" id="sub_product">
<option value="1">Perorangan</option>
<option value="2">Home Visit</option>
<option value="3">Corporate</option>
</select>
</div>
</div>
<div class="p-2">
<div class="form-group">
<label class="form-label font-weight-bold" for="appoinment_date">Tanggal Pelayanan</label>
<input name="appointment_date" placeholder="Tanggal Layanan" id="appointment_date" class="form-control datepicker" autocomplete="off">
</div>
</div>
You have to write some JS to your form with event listener:
document.querySelector('#sub_product').addEventListener('change', () => {
// your code
})
I made codepen for you with an example:
https://codepen.io/VeterJS/pen/BaRvYYx
Is easier with jQuery, when the Corporate option is selected the div display containing the radio buttons is changed to block and when other option is selected then the display goes back to none which hides the element.
$("select").change(function() {
let option = '';
$("select option:selected").each(function() {
option = $( this ).text();
});
if(option == 'Corporate'){
$('#radioBTNS').css('display','block')
}else{
$('#radioBTNS').css('display','none')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p-2">
<div class="form-group">
<label class="form-label font-weight-bold" for="sub_product">Jenis Layanan</label>
<select class="form-control" name="sub_product" id="sub_product">
<option value="1">Perorangan</option>
<option value="2">Home Visit</option>
<option value="3">Corporate</option>
</select>
</div>
</div>
<div id="radioBTNS" style="margin:10px;display:none">
<input type="radio" id="age1" name="age" value="30">
<label for="age1">Radio btn one</label><br>
<input type="radio" id="age2" name="age" value="60">
<label for="age2">Radio btn two</label><br>
</div>
<div class="p-2">
<div class="form-group">
<label class="form-label font-weight-bold" for="appoinment_date">Tanggal Pelayanan</label>
<input name="appointment_date" placeholder="Tanggal Layanan" id="appointment_date" class="form-control datepicker" autocomplete="off">
</div>
</div>

get value from form select and then calculate value in an input

I am trying to calculate multiple values based on multiple selections from a and then have the data add up and display in an on the same form. I tried some jquery stuff but didn't really work at all. I've tried using some Javascript to do the calcultions but nothing seems to be happening.
Blade:
#extends('layout.layouts')
#section('content')
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NCIC - Reports</title>
</head>
<body>
<br>
<h1>New Report</h1>
<br>
<form action="{{ 'storereport' }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="author">Reporting Officer</label>
<input type="text" class="form-control" name="author" value="{{ Auth::user()->name }}">
</div>
<div class="form-group">
<label for="profileid">SSN</label>
<input type="text" class="form-control" name="profileid">
</div>
<div class="form-group">
<label for="report">Report</label>
<textarea class="form-control" name="report" rows="10"></textarea>
</div>
<div class="form-group">
<label for="selectpicker">Select Offences</label>
<select class="selectpicker" id="lawspicker" name="laws[]" data-width="100%" data-live-search="true" multiple>
#foreach($laws as $law)
<option value="{{ $law->name }} {{ $law->fine }} {{ $law->months }}">Offence: {{ $law->name }} </option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="punishment">Punishment</label>
<input type="text" class="form-control" id="punishment" name="punishment">
</div>
<hr style="background-color:white;">
<button type="submit" class="btn btn-success">Submit</button>
<a class="btn btn-info float-right" href="{{ route('reports') }}">Main menu</a>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$("#lawspicker").keyup(function(){
$("#punishment").val(parseFloat($("{{ $law->months }}").val()) + parseFloat($('{{ $law->fine }}').val()));
})
$("#lawspicker").change(function(){
$("#punishment").val(parseInt($("#lawspicker").val());
})
</script>
<style>
body{
background-color: #353b48;
color:white;
}
</style>
</html>
#endsection
To clarify, I want {{ $law->months }} & {{ $law->fine }} to add up and then display in #punishment <input>
Thanks for looking!
You can do some thing like this.
Update <option> tag to this
<option data-fine="{{$law['fine']}}" data-months="{{$law['months']}}" value="{{ $law['name'] }} {{ $law['fine'] }} {{ $law['months'] }}">Offence: {{ $law['name'] }} </option>
and you can get data attribute of the selected <option> tag in your script like this.
`$("#lawspicker").change(function() {
var fine = $(this).find(':selected').data('fine');
let months = $(this).find(':selected').data('months');
$("#punishment").val(parseInt(fine+months));
});`
Thanks.
I would be tempted to replace your select element with checkboxes personally.
An example below using jquery to calculate the fine and months when a button is clicked but could be an event of your choosing. I stripped it back from your example so it was easier to see what is going on.
Checkbox example
<div class="container mt-4">
<div class="row">
<div class="col-12">
<div class="form-group">
<h4>Select Offences</h4>
<div class="d-flex">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="laws[]" id="law-a" data-fine="100" data-months="12" class="custom-control-input offence">
<label for="law-a" class="custom-control-label">Law A</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="laws[]" id="law-b" data-fine="999" data-months="6.5" class="custom-control-input offence">
<label for="law-b" class="custom-control-label">Law B</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="laws[]" id="law-c" data-fine="123.5" data-months="8" class="custom-control-input offence">
<label for="law-c" class="custom-control-label">Law C</label>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="punishment">Punishment</label>
<input type="text" class="form-control" id="punishment" name="punishment" readonly>
</div>
</div>
<div class="col-12">
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
Then some javascript (jquery)
$(function() {
$("#submit").click(function() {
let fine = 0;
let months = 0;
$(".offence").each(function(index, obj) {
if (obj.checked) {
fine += parseFloat($(obj).data("fine"));
months += parseFloat($(obj).data("months"));
}
})
$("#punishment").val("Fine: "+ fine + " Months: " + months);
})
});
When you click submit, the javascript will loop through each element with the offence class and then read the value of the data-fine and calculate the totals.
An example fiddle: https://jsfiddle.net/dbtas60w/
Multiselect example
<div class="container mt-4">
<div class="row">
<div class="col-12">
<div class="form-group">
<h4>Select Offences</h4>
<div class="d-flex">
<div class="custom-control custom-checkbox">
<select class="selectpicker" id="lawspicker" name="laws[]" multiple>
<option data-fine="100" data-months="12">Law A</option>
<option data-fine="999" data-months="6.5">Law B</option>
<option data-fine="123.5" data-months="8">Law C</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="punishment">Punishment</label>
<input type="text" class="form-control" id="punishment" name="punishment" readonly>
</div>
</div>
<div class="col-12">
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
javascript
$(function() {
$("#submit").click(function() {
let fine = 0;
let months = 0;
$("#lawspicker>option").each(function(index, obj) {
if (obj.selected) {
fine += parseFloat($(obj).data("fine"));
months += parseFloat($(obj).data("months"));
}
})
$("#punishment").val("Fine: "+ fine + " Months: " + months);
})
});
Example fiddle: https://jsfiddle.net/dbtas60w/1/

Last-child not working inside iteration of div

In browser, the HTML is generated dynamically and is rendered as
<div id="dynamic-relationship-details">
<div id="count-status0" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type0" class="form-control"><option value="">Select Relationship</option><option value="Father">Father</option><option value="Mother">Mother</option><option value="Brother">Brother</option><option value="Sister">Sister</option><option value="Spouse">Spouse</option><option value="Guardian">Guardian</option></select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name0" id="relationship-type-name0" class="form-control" placeholder="Name"></div><div class="col-sm-2"><input type="text" name="relationship-type-contact0" id="relationship-type-contact0" class="form-control" placeholder="Contact Number">
</div>
<button value="count-status0" class="remove-relationship-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div><div id="count-status1" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type1" class="form-control"><option value="">Select Relationship</option><option value="Father">Father</option><option value="Mother">Mother</option><option value="Brother">Brother</option><option value="Sister">Sister</option><option value="Spouse">Spouse</option><option value="Guardian">Guardian</option></select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name1" id="relationship-type-name1" class="form-control" placeholder="Name"></div><div class="col-sm-2"><input type="text" name="relationship-type-contact1" id="relationship-type-contact1" class="form-control" placeholder="Contact Number">
</div>
<button value="count-status1" class="remove-relationship-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
</div>
The code is
// Relationship details Array
$(".relationship-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").each(function() {
var relationshipTypeValue = $(this).val();
var relationshipName =$this.find("input[type=text]:first-child").val();
var relationshipContactNumber =$this.find("input[type=text]:last-child").val();
var innerRelationshipArray = {};
innerRelationshipArray = {
relationshipTypeValue: relationshipTypeValue,
relationshipName: relationshipName,
relationshipContactNumber: relationshipContactNumber
};
relationship_details_array.push(innerRelationshipArray);
});
});
I am trying to fetch values of contact numbers i.e with id's relationship-type-contact(n) values in the line "
var relationshipContactNumber =$this.find("input[type=text]:last-child").val();"
This is fetching values of first-child textboxes in the variable relationshipContactNumber in the loop.
Please help !!!
This should work, use the .first() and .last() selectors.
Another way, if you have access to alter the HTML, is to add class names for the input fields and select them by using that instead.
function getData() {
var relationship_details_array = [];
// Relationship details Array
$(".relationship-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").each(function() {
var relationshipTypeValue = $(this).val();
var relationshipName = $this.find("input[type=text]").first().val();
var relationshipContactNumber = $this.find("input[type=text]").last().val();
var innerRelationshipArray = {};
innerRelationshipArray = {
relationshipTypeValue: relationshipTypeValue,
relationshipName: relationshipName,
relationshipContactNumber: relationshipContactNumber
};
relationship_details_array.push(innerRelationshipArray);
});
});
console.log(relationship_details_array);
}
$("#getData").on("click", getData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="getData">Show data in console log</button>
<div id="dynamic-relationship-details">
<div id="count-status0" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type0" class="form-control">
<option value="">Select Relationship</option>
<option value="Father">Father</option>
<option value="Mother" selected>Mother</option>
<option value="Brother">Brother</option>
<option value="Sister">Sister</option>
<option value="Spouse">Spouse</option>
<option value="Guardian">Guardian</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name0" id="relationship-type-name0" class="form-control" value="Mommy" placeholder="Name">
</div>
<div class="col-sm-2">
<input type="text" name="relationship-type-contact0" id="relationship-type-contact0" class="form-control" value="1234" placeholder="Contact Number">
</div>
</div>
<div id="count-status1" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type1" class="form-control">
<option value="">Select Relationship</option>
<option value="Father" selected>Father</option>
<option value="Mother">Mother</option>
<option value="Brother">Brother</option>
<option value="Sister">Sister</option>
<option value="Spouse">Spouse</option>
<option value="Guardian">Guardian</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name1" id="relationship-type-name1" class="form-control" value="Daddy" placeholder="Name">
</div>
<div class="col-sm-2">
<input type="text" name="relationship-type-contact1" id="relationship-type-contact1" class="form-control" value="5678" placeholder="Contact Number">
</div>
</div>
</div>

Categories