Trying to pass a variable to Jquery from Razor - javascript

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

Related

how to filup the textbox value after popup the bootstrap modal

I am trying to fillup textbox value when user select the value from the dropdownlist
but issue is my dropdownlist is coming when click on apply link
see below image when I click the apply button then open bootstrap model
I write the code for change the value of dropdownlist an fillup that value in another textbox
.cshtml
<div class="row">
<div class="col-md-2">
<label>Vacancy:</label>
</div>
<div class="col-md-8">
<select id="hm" class="form-control">
#foreach (var item in #ViewBag.vacancy)
{
<option value="item.vacancytitle">
#item.vacancytitle
</option>
}
</select>
</div>
</div>
<br />
<div class="row">
<div class="col-md-2">
<label>vacancyid:</label>
</div>
<div class="col-md-8">
<input class="form-control" type="text" id="vacancyid" value="" />
</div>
</div>
<br />
<div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('#applylink').click(function () {
debugger
//var h = document.getElementById(hm).value;
//var strUser = h.options[e.selectedIndex].value;
//$('#vacancyid').val(strUser);
$("#myModal").modal(); //here open bootstrap modal
$('#hm').on('change', function () {
var selectVal = $("#selectId option:selected").val();
$('#vacancyid').val(selectVal); //here I am trying to fetch value from dropdownlist when user select the particular value from the dropdownlist
});
});
</script>
currently I have two value in dropdownlist
html/css developer
angular,js developer
when user select html/css developer from the dropdownlist then here I am filling
$('#vacancyid').val(selectVal);
html/css developer
first click the apply link button and then open bootstrap modal
I want to fillup textbox value when user select the value from the dropdownlist
when open the popup then I want to call this method
$('#hm').on('change', function () {
var selectVal = $("#selectId option:selected").val();
$('#vacancyid').val(selectVal); //here I am trying to fetch value from dropdownlist when user select the particular value from the dropdownlist
});
Edit:
//load javascript after modal is loaded
//load option value chage after modal is loaded
$(document).ready(function () {
debugger
$('#myModal').on('load', function () {
debugger
$('#hm').on('change', function () { //debugger here not come when select the value from the dropdownlist
debugger
var selectVal = $("#selectId option:selected").val();
$('#vacancyid').val(selectVal);
});
});
});
You can simply use the native BS function like shown.bs.modal. Your load function is not doing anything when the modal shows so your change function is not working at all.
Also, since you want load the vacancyId value from dropdown- You can simply assign the option the value of #item.vacancyId
<select id="hm" class="form-control">
#foreach (var item in #ViewBag.vacancy)
{
<option value="#item.vacancyid">
#item.vacancytitle
</option>
}
</select>
Load the boostrap modal like this:
$(document).ready(function() {
$('#myModal').on('shown.bs.modal', function() {
$('#hm').on('change', function() {
var selectVal = $(this).val();
$('#vacancyid').val(selectVal);
}); //this method work now :)
})
});
You can use show event for bootstrap modal. See this.
Like as in the following code:
$('#myModal').on('shown.bs.modal', function() {
// your code goes here
})

Capture Selected Values from Dynamic Drop-down Lists using 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();

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>');
}
});

Add fields to laravel form dynamically

I have a Laravel form that collects info from a user. On one part of the form I want to add a button that will add a row containing 4 text boxes (each named differently) that the user can fill in. Each time the user clicks the button, another row of 4 text boxes should be added.
In an ideal world, the code will be a javascript function (so I can reuse it later) called by a button click. I can't seem to see how to add an event handler to a button click on a laravel form.
This works
HTML
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
JS
$(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
$("#rm").remove();
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/>'); //add input box
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/>'); //add input box
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/></div>'); //add input box
$(wrapper).append('<div id="divs"><input type="text" name="mytext[]"/>Remove</div>'); //add input box
$(wrapper).append('<br>')
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $("#divs").remove(); x--;
$("#divs").remove(); x--;
$("#divs").remove(); x--;
$("#divs").remove(); x--;
})
});
the name will be mytext (first input name = mytest[1] second mytest[2] ...etc)
you can add the X variable to the form so you know how many input you have in your controller
in the html , you can change the type to hidden so you want have any input fields untill user click
check result this in JSFiddle

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.

Categories