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>');
}
});
Related
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>×</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();
I have a "Try Again!" message that appears when the inserted value exists in my dropdown select list, this is my code:
//I am trying to remove this message once the user starts typing again:
$('#new_day').on('input', function(){
//Get input value
var input_value = $(this).val();
//Remove disabled from the button
$('#new_day_save').removeAttr('disabled');
//iterate through the options
$(".days > option").each(function() {
//If the input value match option text the disable button
if( input_value == $(this).text()){
$('#new_day_save').attr('disabled', 'disabled');
$('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>");
}else{
$('#new_day_save').parent().remove("#error_message");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="days">
<option>Monday</option>
<option>Friday</option>
</select>
<p>You have another proposition? Add it to the list.</p>
<div>
<input id="new_day" type="text" />
</div>
<input id="new_day_save" type="button" value="save new day"/>
you can just remove the #error_message by adding this to your event handler just before you compare input value to option
$('#new_day_save').parent().find('#error_message').remove()
and you can remove the else condition.
$('#new_day').on('input', function(){
//Get input value
var input_value = $(this).val();
//Remove disabled from the button
$('#new_day_save').removeAttr('disabled');
$('#new_day_save').parent().find('#error_message').remove();
//iterate through the options
$(".days > option").each(function() {
//If the input value match option text the disable button
if( input_value == $(this).text()){
$('#new_day_save').attr('disabled', 'disabled');
$('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="days">
<option>Monday</option>
<option>Friday</option>
</select>
<p>You have another proposition? Add it to the list.</p>
<div>
<input id="new_day" type="text" />
</div>
<input id="new_day_save" type="button" value="save new day"/>
This line $('#new_day_save').parent().remove("#error_message"); will remove parent element.
To remove specific element in jQuery, do simply since it's a id selector which is unique element,
$("#error_message").remove();
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
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.
I have a form that you can add fields: http://jsfiddle.net/ytrkqr6a/2/
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //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 class="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control cameras" readonly /> Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>
<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control cameras" readonly /></div>
</div>
Everything works fine adding fields, but where I'm hung up is when you remove one of the fields then numerical order gets off.. how do I make it update the remaining fields to stay in proper numerical order each time you add or remove a field:
Camera 1
Camera 2
Camera 3
etc...
Thanks ahead of time!
I just added a jQuery "each" loop to re placerholder, name, and value each input field every time a remove link is clicked. When using each the value passed to the function is the index of item in the loop's current iteration, I used the variable elm. Since each input field is classed with camerasCounter, you can use $(this) to easily call the input element in the loop. Each is a very useful part of jQuery, if you ask me.
http://jsfiddle.net/v76zn30o/2/
The HTML
<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>
<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control camerasCounter" readonly /></div>
</div>
and The jQuery
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //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 class="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control camerasCounter" readonly /> Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
$(".camerasCounter").each(function(elm){
x = elm + 1
$(this).attr({
"placeholder": "Camera " + x,
"name": "Camera " + x,
"value": "Camera " + x
});
});
});
});