Capture Selected Values from Dynamic Drop-down Lists using Javascript - javascript

I'm trying to get the value from dynamic drop-down list in my form, but my code isn't working.
View.php
<div class="input_fields_wrap">
<input type="button" class="btn btn-info add_field_button" value="Tambah Cara Pengolahan" /> <br /><br />
</div>
<div class="service-container" data-service=
"<div class='form-group'>
<select class='form-control' style='width:88%; display:inline-block; margin-right:10px;' name='cara_pengolahan[]' required>
<option value=''>No Selected</option>
<?php foreach($pengolahan as $row):?>
<option value='<?php echo $row->id_pengolahan;?>'><?php echo $row->cara_pengolahan;?></option>
<?php endforeach;?>></div>
</select>
<button class='btn btn-danger closebtn remove_field'><b>&times</b></button>
</div>"
</div>
Javascript.js
$('.service-container').each(function() {
var container = $(this);
var service = container.data('service');
// Service variable now contains the value of html + php variable;
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(service);
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
var cara_pengolahan = document.forms[0].elements["cara_pengolahan[]"];
if(typeof cara_pengolahan !== 'undefined'){
for (var i=0; i<cara_pengolahan.length; i++) {
console.log(cara_pengolahan[i].value);
}
}
When there is one dynamic drop-down list, it returns all the array values of it. But what I want is to capture the selected value of that drop-down list.
And when there are more than one dynamic drop-down lists, it returns the correct selected values of that drop-down lists.
How to capture the selected value of all the dynamic drop-down lists?
Thanks in advance.

Try this:
myval= $("#id").find("option:selected").val();
Where #id is the id of your select input

To check if there is a dynamic Drop down you can simple check if the selector exists
with
$('#elemId').length>0
And for selected value you can use $("#selectorid").find("option:selected").val();

Related

Jquery removing dynamic drop down removes entire parent div

I am trying to add drop down on click of button.
From the 2nd drop down on wards, there is a remove button , which basically will remove the drop down.
The problem is when i click the remove link, the entire div is getting removed, even the 1st drop down.
I want only that corresponding drop down to be deleted .
<div class="row myccccccbackground" style="padding: 5px;margin: 265px 0 6px;"><span class="content_shorting"> <?php echo $this->translate('Call for action button 1');?><img class="Text_Action_bt1_tooltip" data-toggle="tooltip" data-placement="right" style="margin: 0px 0px -7px 3px;" src="<?=$this->basePath()?>/images/info_icon_grey.png"></span><br/><br/>
<br>
<button type='button' id = "btnAdd" style="position: relative;bottom: 24px;" >Add another...</button><br/><br/>
<div class="fields_action"><br>
<select id="action" class="increment" style="position: relative;bottom: 32px;">
<option value="N">Select Action</option>
<option value="Y">SMS</option>
<option value="Y">Call</option>
<option value="Y">Call Back</option>
<option value="Y">Email</option>
<option value="Y">Website </option>
</select><br/>
<span style="color:red;" class="key-error-class" id="key_error_1" ></span>
<span id="valueResponse_1" class="valueResponse-class"></span>
</div>
</div>
JS:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".fields_action"); //Fields wrapper
var add_button = $("#btnAdd"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
var actionid = $('#action');
//UPDATED
if (actionid.val() === '' || actionid.val() === 'N') {
alert("Please select an item from the list and then proceed!");
$('#action').focus();
return false;
}
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select id="action" class="increment"><option value="N">Select Action</option><option value="Y">Call</option><option value="Y">Call Back</option><option value="Y">Email</option><option value="Y">Website </option></select> <input name="TextAdPriority" class="adtitle nospaceallow integeronly" value="" type="text">Remove<br/></div>');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
UPDATE: The above validation check - ie) if default option is selected then the alert is thrown only for 1st drop down.
How to check for default value from the 2nd drop down.
You missed to add <div> at the begining of append method.
Here is complete code.
$(wrapper).append('<div><select id="action" class="increment"><option value="N">Select Action</option><option value="Y">Call</option><option value="Y">Call Back</option><option value="Y">Email</option><option value="Y">Website </option></select> <input name="TextAdPriority" class="adtitle nospaceallow integeronly" value="" type="text">Remove<br/></div>');
To validate multiple dropdowns you can modify your code following way. It is working fine for me.
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
//UPDATED
var dropdowns = $('.increment');
var isValid = true
dropdowns.map(function(idx, dropdown) {
if (dropdown.value === '' || dropdown.value === 'N') {
alert(`Please select an item on position ${idx+1} dropdown and then proceed!`);
$(dropdown).focus();
isValid = false;
}
})
if(isValid && x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select id="action" class="increment"><option value="N">Select Action</option><option value="Y">Call</option><option value="Y">Call Back</option><option value="Y">Email</option><option value="Y">Website </option></select> <input name="TextAdPriority" class="adtitle nospaceallow integeronly" value="" type="text">Remove<br/></div>');
}
});

Issue with using javascript plugin with input array

I have a simple text input using the timepicki jquery plugin. I am able successfully use the plugin on my first text input, but I am not able to use it on the additional inputs created by array as shown.
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$('#timepicker').timepicki(); //Call Timepicki plugin for #timepicker ID
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="timepicker[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<html>
Ring Time:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" id='timepicker' type='text'name='timepicker[]'"></div>
</div><br><br>
</html>
My question is - How can can enable it so that all instances of the timepicker input can use the timepicker plugin?
Thanks!
Theres a couple of changes that should make it work
$('.timepicker').timepicki(); //class instead of id
and in your HTML and javascript
<input type="text" class="timepicker" name="timepicker[]" />
in the click function
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" class="timepicker" name="timepicker[]"/>Remove</div>');
}
$('.timepicker').timepicki();
});

Trying to pass a variable to Jquery from Razor

So I'm working on a project in ASP.net and have a situation where I've created a form that provides users a drop down menu to select from. On top of this the Jquery below allows the user to add additional drop down fields. This works.
Now my problem stems from the first drop down has a list of institutes which works fine as its being populated from the C# in the html form.
When the user selects to add another drop down that box is just empty. I've tried adding the C# directly to the Jquery but this doesn't work.
I'm not overly experienced with ASP.net or MVC both of which I'm using for the project, what is the best way to go around passing the values into Jquery so I can add list to the drop down?
Here is the code below
<script>
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" /></select>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Here is the HTML
<div class="col-md-3 BasicInfoFormLabelColumn">
<label for="restrictedInstitute" class="formLabel">Restricted Institutes: (Can't Apply)</label>
</div>
<div class="col-md-3 input_fields_wrap">
<select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
<option value="0">Please Select</option>
#foreach (var item in Model.institute)
{
if (#item.TradingName != null && #item.TradingName != " " && #item.TradingName != "")
{
<option value="#item.TradingName">#item.TradingName</option>
}
}
</select>
<div class="row">
<div class="col-md-12 BasicInfoFormRow ">
<button class="add_field_button addMore">+Add More institutes</button>
</div>
</div>
</div>
I've added a couple images to help clarify what I'm trying to do.
Its happening because U only append select without its option inside you Jquery. I recommend using AJAX and partial view to achieve ur goal.
First, separate the rendering of dropdownlist into another cshtml, for example the name is Institute.cshtml
Institute.cshtml
#model xxxx.Model.Institute //model would be your institute
<select style="padding-left: 5px; width: 100%;" class="BasicInfoFormControl" onblur="" name="restrictedInstitute[]" id="selectRestricted" />
<option value="0">Please Select</option>
#foreach (var item in Model)
{
if (#item.TradingName != null && #item.TradingName != " " && #item.TradingName != "")
{
<option value="#item.TradingName">#item.TradingName</option>
}
}
</select>
Then you call it as partialview in your HTML
<div class="col-md-3 input_fields_wrap">
#Html.Partial("Institute", Model.Institute)
<div class="row">
<div class="col-md-12 BasicInfoFormRow ">
<button class="add_field_button addMore">+Add More institutes</button>
</div>
</div>
</div>
And add the partialview in your Controller
xxController
PartialViewResult Institute()
{
return PartialView();
}
This is the first step to separate your dropdownlist into another partialView
The second step is calling an ajax in your add click button, and fetch the result using this partialView
javascript
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function{ //on add input button click
if (x < max_fields) { //max input box allowed
x++; //text box increment
$.ajax({
url: '#Url.Action("AddDropdown", "YourController")',
type: "GET",
success: function (result) {
$(wrapper).append(result);
}
});
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
this Javascript means, when u click Add button, you will request to your controller using Ajax. Then the controller will help you to render the dropdownlist and send the result back to your Client.
So, you need to add another function in your controller to receive this Ajax request
xxController
public ActionResult AddDropdown()
{
Model.Institute Result = new Model.Institute()
//you can generate your Model.Institue in here
Return PartialView("Institute", Result); //this will render Result with Institute.cshtml
}
after this, you can add dropdownlist into your html with the click add button

Input field not removed when populated dynamically through database using javascript

I am using javascript to add and delete input fields. Fields are properly added, data is saved and displayed too. But when I click remove button in the field that is generated from database, it is not removed. It takes me to the top of the page. But if I click add more fields, new field is generated through javascript and it is removed when I click its remove. Where am I wrong?
HTML AND JAVASCRIPT
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
</div>
<?php
// retrieve the user meta
$fb = get_user_meta($user->ID, 'business_sm_fb', false);
if (!empty($fb)) {
?>
<?php foreach ($fb as $f_b) {
?>
<?php foreach ($f_b as $val) { ?>
<div><input type="text" name="sm_fb[]" type="text" class="regular-text" value="<?php echo $val; ?>" />Remove</div>
<?php
}
}
?>
<?php } else {
?>
<div><input type="text" name="sm_fb[]" type="text" class="regular-text" /></div>
<?php } ?>
<script>
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="sm_fb[]" type="text" class="regular-text" />Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
</script>
the issue seems to be related to the wrapper object:
var wrapper = $(".input_fields_wrap");
In your script you bind the click event to all the .remove_field items, that are inside the wrapper object:
$(wrapper).on("click", ".remove_field", function (e) {
....
})
The problem is that the .remove_field items are added via PHP on the outside of the .input_fields_wrap div, therefore the click event does not work.
As you can see here, the .input_fields_wrap is opened and immediately closed after the <button />. Your PHP code adds the inputs outside this div.
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
</div>
To solve the issue, move the closing div tag after the PHP code block.

PHP, JQuery - How to dynamically add more fields consist of dropdownlist(value from database, and a text box)

I have 2 form component that i would like to add dynamically (allow user to add more than 1)
First i have a dropdownlist with values populated from MySQL. Followed by a text box which allows user to enter some enquires.
Basically, the dropdownlist will show a list of user and a textbox for the person to type a message to the person.
The user is allow to send to multiple different user, therefore there is a ADD button which will add another dropdownlist and a text box..
I tried using jQuery append. but append does not accepts PHP as its server side.
I also tried to jQuery clone to clone the whole DIV but fails.
I am using this code to add field dynamically
Add Remove field dynamically
This is my code for the dropdownlist and textbox
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<select name="msgrecever1" style="background:#252525" >
<option value="">Select Faculty</option>
<?php
require_once("../dbconnection/dbcon.php");
$sql="SELECT * FROM user WHERE role='Faculty'";
$records=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($records)){
$name=$row['username'];
echo "<option value='$name'>".$name."</option>";
}
?>
</select><input type="text" name="mytext[]"></div>
I want to duplicate as many of the above code as long as the user press "add new field"
jQuery:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type=\"text\" name=\"mytext[]\"/>Remove');
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
=================
EDITED:
i have used this solution and it works.
<?php require_once("../dbconnection/dbcon.php");
if(isset($_POST['submit']))
{
$capture_field_vals ="";
foreach($_POST["msgrecipient"] as $key => $text_field)
{
echo "Key: $key; Value: $text_field<br />\n";
echo "<br>";
}
foreach($_POST["enquiry"] as $key => $text_field2)
{
echo "Key: $key; Value: $text_field2<br />\n";
echo "<br>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // the numeric ID of the new input field being added
newElem = $('#testingDiv' + num).clone().attr('id', 'testingDiv' + newNum).fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
newElem.find('.test-select').attr('id', 'ID' + newNum + '_select').attr('name', 'ID' + newNum + '_select').val('');
newElem.find('.test-textarea').val('');
// insert the new element after the last "duplicatable" input field
$('#testingDiv' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled', false);
// right now you can only add 5 sections. change '5' below to the max number of times the form can be duplicated
if (newNum == 5) $('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit");
});
$('#btnDel').click(function () {
// confirmation
if (confirm("Are you sure you wish to remove this section of the form? Any information it contains will be lost!")) {
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#testingDiv' + num).slideUp('slow', function () {
$(this).remove();
// if only one element remains, disable the "remove" button
if (num - 1 === 1) $('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "[ + ] add to this form");
});
}
return false;
// remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled', false);
});
$('#btnDel').attr('disabled', true);
});
</script>
</head>
<body>
<form action="#" method="post">
<!--
########################################## -->
<!-- START CLONED SECTION -->
<!-- ########################################## -->
<div id="testingDiv1" class="clonedInput">
<select name="msgrecipient[]" id="select">
<option value="">Select Faculty</option>
<?php
require_once("../dbconnection/dbcon.php");
$sql="SELECT * FROM user WHERE role='Faculty'";
$records=mysqli_query($con,$sql);
while($row=mysqli_fetch_assoc($records)){
$name=$row['name'];
echo "<option value='$name'>".$name."</option>";
}
?>
</select>
<textarea id="textarea" name="enquiry[]" class="test-textarea"></textarea>
</div>
<!--/clonedInput-->
<!-- ########################################## -->
<!-- END CLONED SECTION -->
<!-- ########################################## -->
<!-- ADD - DELETE BUTTONS -->
<div id="add-del-buttons">
<input type="button" id="btnAdd" value="[ + ] add to this form">
<input type="button" id="btnDel" value="[ - ] remove the section above">
</div>
<!-- /ADD - DELETE BUTTONS -->
<input type="submit" name="submit"class="button button-block" value="Submit"/>
</form>
</body>
</html>
Assuming you have a markup like this:
<form id="faculty_wrapper">
<div class="faculty_row">
<select id="faculty" name="faculty[]">
<option value="faculty_one">faculty_one</option>
<option value="faculty_one">faculty_two</option>
<option value="faculty_one">faculty_three</option>
<option value="faculty_one">faculty_four</option>
</select>
<input type="text" name="message[]">
</div>
</form>
Add More <!-- Add More Rows -->
Submit <!-- Submit Button for further work -->
Javascript:
jQuery(document).ready(function($){
$("#add_more").on('click', function(e){
e.preventDefault(); // Prevent Default the event
var clone = $(".faculty_row").eq(0).clone(); // clone only first item
$("#faculty_wrapper").append(clone); // append it to our form
});
$("#submit").on('click', function(e){
e.preventDefault();
alert($("#faculty_wrapper").serialize()); // get serialize data for further work
})
})
You can check the working Jsfiddle.

Categories