Reputation: 143
I have some problems getting a value from my dynamic textboxes. My textboxes look like this:
This is my HTML code to get values:
$('#pilihtambahan input[type=text]').each(function(index) {
if (valData2 == "") {
valData2 = valData2 + $(this).val();
} else {
valData2 = valData2 + "," + $(this).val();
}
});
If I insert a value in textbox "jumlah sewa showcase" with "1" and insert text in "jumlah sewa stove" textbox with "2" the result will be like this
1,<null>,2
I have no idea to remove the null
value. My goal is the result will be like this
1,2
Maybe someone can help me to solve this. Thank you.
Upvotes: 1
Views: 979
Reputation: 452
Here you go
$('.btn').on('click', function() {
arr = [];
$('input[type=text]').each(function() {
var value = $(this).val();
//if(value){
if (value.length) {
arr.push(value);
}
});
console.log(arr);
$('p').html(arr)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<br />
<input type="text">
<br />
<input type="text">
<br />
<button class="btn">
test
</button>
<p>
</p>
Upvotes: 1
Reputation: 29683
Check with $(this).val().length
or $(this).val()!=""
Your modified code would be:
$('#pilihtambahan input[type=text]').each(function(index) {
var val = $(this).val();
if (val.length) {
if (valData2 == "") {
valData2 += valData2 + val;
} else {
valData2 = valData2 + "," + val;
}
}
});
OR
$('#pilihtambahan input[type=text]').each(function(index) {
var val = $(this).val();
if (val !="" && val!=null) {
if (valData2 == "") {
valData2 = valData2 + val;
} else {
valData2 = valData2 + "," + val;
}
}
});
To enhance more you could do:
$('#pilihtambahan input[type=text]').each(function(index) {
var val = $(this).val();
if (val.length) {
if (valData2 == "") {
valData2 += val;
} else {
valData2 += "," + val;
}
}
});
Upvotes: 1
Reputation: 337580
You could check the length
property of the value before you append it to the string.
However a better method would be to build an array of the values using map()
then join()
them together. As an empty string value is falsy you can use a ternary expression within map()
to return the required value or skip it entirely. Try this:
var values = $('#pilihtambahan input[type=text]').map(function(index) {
return this.value ? this.value : null;
}).get().join(',');
Upvotes: 3