JQuery Replace Function Did Not Work On Certain Select Dropdown - javascript

What I want to do is replace the id for every input. I have several inputs in my page.
This is the coding for some user input
<div class="row">
<div class="col">
<div class="form-group row">
<label class="col-md-2 col-form-label" for="daddr3_1">Address 3:</label>
<div class="col-md-9">
<input class="form-control" rows="1" maxlength="30" type="text" id="daddr3_1" name="daddr3[]" placeholder="Third line of address as in Identity Card (optional)">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<?php
include_once "common.php";
$common = new Common();
$countries = $common->getCountry($connection);
?>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="countryId_1">Country:</label>
<div class="col-md-5">
<select name="countryId[]" id="countryId_1" class="form-control" onchange="getStateByCountry();">
<option>Country</option>
<?php
if ($countries->num_rows > 0 ){
while ($country = $countries->fetch_object()) {
$countryName = $country->name; ?>
<option value="<?php echo $country->id; ?>"><?php echo $countryName;?></option>
<?php }
}
?>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="stateId_1">State:</label>
<div class="col-md-5">
<select name="stateId[]" id="stateId_1" class="form-control" onchange="getCityByState();getPostalByState()">
<option>State</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="cityDiv_1">City:</label>
<div class="col-md-5">
<select name="cityDiv[]" id="cityDiv_1" class="form-control">
<option value="">City</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="dpostal">Postal:</label>
<div class="col-md-5">
<select name="postalDiv[]" id="postalDiv_1" class="form-control">
<option>Postal</option>
</select>
</div>
</div>
</div>
</div>
I want to increase the _1 of the input if user add more than one item by duplicating the form.
This is the script to replace the _1 everytime user duplicate the form.
var attrs = ['for', 'id', 'name'];
function resetAttributeNames(section) {
var tags = section.find('input, label, select'), idx = section.index();
tags.each(function() {
var $this = $(this);
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx + 1)))
}
})
})
}
As you can see, in user input for country, state, city, and postal I used onchange function. I wonder if it ain't working because of the onchange function. Because the id can be replaced for Address 3 input. Only the list I mention above is not working.
This is the script of onchange function
<script>
function getStateByCountry() {
var countryId = $("#countryId_1").val();
$.post("ajax.php",{getStateByCountry:'getStateByCountry',countryId:countryId},function (response) {
var data = response.split('^');
$("#stateId_1").html(data[1]);
});
}
function getCityByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getCityByState:'getCityByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#cityDiv_1").html(data[1]);
});
}
function getPostalByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getPostalByState:'getPostalByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#postalDiv_1").html(data[1]);
});
}
function enable(){
var check = document.getElementById("check");
var btn = document.getElementById("btn");
if(check.checked){
btn.removeAttribute("disabled");
}
else{
btn.disabled = "true";
}
}
</script>
Any help is appreciated :)

Related

Codeigniter image upload with Javascript

Problem: Working on a save product information page here I wanted to upload images using Codeigniter and Javascript. Other text boxes and select box data save function working fine. Tried following code but it shows error: You did not select a file to upload.
Please help me to solve this error and upload an image file.
Code:
View: addProduct.php
<div class="tz-2 tz-2-admin">
<div class="tz-2-com tz-2-main">
<h4>Add New Product</h4>
<div class="split-row">
<div class="col-md-12">
<div class="box-inn-sp ad-inn-page">
<div class="tab-inn ad-tab-inn">
<div class="hom-cre-acc-left hom-cre-acc-right">
<div class="">
<form class="">
<span id="statusBar"></span>
<div class="row">
<div class="input-field col s12">
<input id="prod_id" type="text" class="validate" disabled>
<label id="lblProdId" for="prod_id">Product ID</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_name" type="text" class="validate">
<label for="prod_name">Product Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_short_name" type="text" class="validate">
<label for="prod_short_name">Short Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_cat" class="validate">
<option value="">-- Select Category --</option>
<?php foreach($categories as $Category):?>
<option value="<?php echo $Category->Cat_ID;?>"><?php echo $Category->Cat_Name;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12" >
<select id="prod_brand" class="validate">
<option value="">-- Select Brand--</option>
<?php foreach($brands as $brand):?>
<option value="<?php echo $brand->Brand_ID;?>"><?php echo $brand->Brand_Name;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_mrp" type="text" class="validate">
<label for="prod_mrp">MRP</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_p_price" type="text" class="validate">
<label for="prod_p_price">Purchase Price</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_s_price" type="text" class="validate">
<label for="prod_s_price">Min. Selling Price</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_uom" class="validate">
<option>-- Seletct Unit of Measure --</option>
<option value="Kilos">Kilos</option>
<option value="Liters">Liters</option>
<option value="Meters">Meters</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_size" type="text" class="validate">
<label for="prod_size">Size</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_per_unit" type="text" class="validate">
<label for="prod_per_unit">Products per unit</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_SGST" type="text" class="validate">
<label for="prod_SGST">SGST</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_CGST" type="text" class="validate">
<label for="prod_CGST">CGST</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_IGST" type="text" class="validate">
<label for="prod_IGST">IGST</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_GST_inc" class="validate">
<option value=""selected>Is Inclusive GST</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_status" class="validate">
<option>-- Select Status </option>
<option value="Enabled">Enabled</option>
<option value="Enabled">Disabled</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="prod_description" class="materialize-textarea validate"></textarea>
<label for="prod_description">Descriptions</label>
</div>
</div>
<div class="row tz-file-upload">
<div class="file-field input-field">
<div class="tz-up-btn"> <span>File</span>
<input type="file" id="prod_image" > </div>
<div class="file-path-wrapper db-v2-pg-inp">
<input class="file-path validate" id="prod_image" type="text">
<label for="prod_image" style="padding-left:12%;" >Product Image</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s12" id="btnSaveProd"> <a class="waves-effect waves-light btn-large full-btn" href="#!" onclick="ajax_addProduct();">Save Product</a> </div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function ajax_addProduct(){
event.preventDefault();
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "<?php echo base_url();?>products/save";
var prod_name = document.getElementById("prod_name").value;
var prod_short_name = document.getElementById("prod_short_name").value;
var prod_cat = document.getElementById("prod_cat").value;
var prod_brand = document.getElementById("prod_brand").value;
var prod_mrp = document.getElementById("prod_mrp").value;
var prod_p_price = document.getElementById("prod_p_price").value;
var prod_s_price = document.getElementById("prod_s_price").value;
var prod_uom = document.getElementById("prod_uom").value;
var prod_size = document.getElementById("prod_size").value;
var prod_per_unit = document.getElementById("prod_per_unit").value;
var prod_SGST = document.getElementById("prod_SGST").value;
var prod_CGST = document.getElementById("prod_CGST").value;
var prod_IGST = document.getElementById("prod_IGST").value;
var prod_GST_inc = document.getElementById("prod_GST_inc").value;
var prod_status = document.getElementById("prod_status").value;
var prod_description = document.getElementById("prod_description").value;
var prod_image = document.getElementById("prod_image").files[0].name;
var vars = "prod_name="+prod_name+"&prod_short_name="+prod_short_name+"&prod_cat="+prod_cat+"&prod_brand="+prod_brand+"&prod_mrp="+prod_mrp+"&prod_p_price="+prod_p_price+"&prod_s_price="+prod_s_price+"&prod_uom="+prod_uom+"&prod_size="+prod_size+"&prod_per_unit="+prod_per_unit+"&prod_SGST="+prod_SGST+"&prod_CGST="+prod_CGST+"&prod_IGST="+prod_IGST+"&prod_GST_inc="+prod_GST_inc+"&prod_status="+prod_status+"&prod_description="+prod_description+"&prod_image="+prod_image;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
if (return_data > 0) {
document.getElementById("statusBar").className = "";
document.getElementById("statusBar").innerHTML = "<p class='alert alert-success' style='font-size:16px; padding-top:2%; text-align:center;'> <strong>Success...!</strong> New category added.</p>";
//var elem = document.getElementById("btnSaveProd");
//elem.parentNode.removeChild(elem);
var elem = document.getElementById("lblProdId");
elem.parentNode.removeChild(elem);
document.getElementById("prod_id").value = return_data;
}
else{
document.getElementById("statusBar").className = "";
document.getElementById("statusBar").innerHTML = return_data;
}
}
else {
document.getElementById("statusBar").innerHTML = return_data;
}
}
if (prod_name != "" && prod_short_name != "") {
hr.send(vars);
document.getElementById("statusBar").className = "alert alert-info";
document.getElementById("statusBar").innerHTML = "processing...";
}
else if(prod_name == ""){
document.getElementById("prod_name").className = "validate invalid";
var elmnt = document.getElementById("statusBar");
elmnt.scrollIntoView();
}
else if(prod_short_name == ""){
document.getElementById("prod_short_name").className = "validate invalid";
var elmnt = document.getElementById("prod_name");
elmnt.scrollIntoView();
}
}
</script>
Controller: Products.php
public function save()
{
$data['Prod_Name'] = $this->input->post('prod_name', TRUE);
$data['Prod_Short_Name'] = $this->input->post('prod_short_name', TRUE);
$data['Cat_ID'] = $this->input->post('prod_cat', TRUE);
$data['Brand_ID'] = $this->input->post('prod_brand', TRUE);
$data['Prod_MRP'] = $this->input->post('prod_mrp', TRUE);
$data['Prod_P_Price'] = $this->input->post('prod_p_price', TRUE);
$data['Prod_S_Price'] = $this->input->post('prod_s_price', TRUE);
$data['Prod_UOM'] = $this->input->post('prod_uom', TRUE);
$data['Prod_Size'] = $this->input->post('prod_size', TRUE);
$data['Prod_Per_Unit'] = $this->input->post('prod_per_unit', TRUE);
$data['Prod_SGST'] = $this->input->post('prod_SGST', TRUE);
$data['Prod_CGST'] = $this->input->post('prod_CGST', TRUE);
$data['Prod_IGST'] = $this->input->post('prod_IGST', TRUE);
$data['Prod_GST_Inclusive'] = $this->input->post('prod_GST_inc', TRUE);
$data['Prod_Status'] = $this->input->post('prod_status', TRUE);
$data['Prod_Description'] = $this->input->post('prod_description', TRUE);
$data['Prod_Image'] = $this->input->post('prod_image', TRUE);
$this->do_upload();
if ($pid = $this->Products_Model->saveProduct($data))
{
echo $pid;
}
else
{
echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong> Unable to add category.</p>";
}
}
public function do_upload()
{
$config['upload_path'] = base_url(). "uploads/";
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('Prod_Image'))
{
$error = array('error' => $this->upload->display_errors());
echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong>".$error['error'].".</p>";
}
else
{
$data = array('upload_data' => $this->upload->data());
echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong>".$data['upload_data'].".</p>";
}
}
Please help me to upload and save filename to the database.
NOTE: Don't want to use Jquery. Please suggest an answer with traditional Javascript.
To submit the form with image and other data, use the below code
<?php echo form_open_multipart('', 'id="your_form_id"'); ?>
<?php echo form_close(); ?>
And script
$("#your_form_id").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "<?php echo base_url();?>products/save",
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
// your code here
},
success: function(json)
{
// your code here
}
});
});

v-for for using loop and select2 not working when using in ajax

why my script not working .
I getting data from ajax and using select2 for selecting products and when I try to use v-for to use loop for add part for each product that selected in prev item .
this is my html :
<div class="item form-group col-md-3 green box" style="display: none">
<label class="control-label" for="name">محصولات سفارشی<span class="required">*</span>
</label>
<select v-model="products_order" class="form-control reagent_selector" name="products_orders[]" multiple="multiple" id="">
#foreach ($products as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select>
<textarea v-model="products_order_desc" v-if="products_order.length > 0" name="products_order_desc" cols="10"
rows="4" class="form-control" style="margin-top: 13px;" placeholder="توضیحات"></textarea>
</div>
<div class="col-md-3">
<div v-for="(order,indexx) in products_order">
<div class="item form-group">
<div>
<label class="control-label" for="name">منبع سفارش : #{{getProductById(order)}} <span
class="required">*</span>
</label>
<select v-model="selectedRes[order]" style="height: 43px;" class="form-control" name="" id="">
<option v-for="(item,index) in resources" :value="item.id">#{{item.name}} : #{{item.resource}}
</option>
</select>
</div>
</div>
</div>
</div>
and this is vue,js
products_order: function () {
let self = this;
let validator;
let irt;
if (self.products_order.length == 0) {
self.selectedRes = {}
}
Object.entries(self.selectedRes).forEach(function (item, ir) {
// console.log(item[0])
validator = false;
irt = null
self.products_order.forEach(function (itemm, indexx) {
if (itemm == item[0]) {
validator = true;
irt = itemm
}
})
if (validator == true) {
alert(irt)
delete self.selectedRes[irt];
}
});
}

How to get values of dynamically generated input fields from jQuery into an JSON object?

I am trying to fetch the data from a form and posting it to server in JSON format. I am facing problem that values of dynamically generated input fields are not getting fetched, only the value of fields that are static and defined in HTML page is getting fetched.
Below is my HTML code of form
<form class="form-horizontal" id="product-form">
<div class="form-group">
<label class="control-label col-sm-2">Category</label>
<div class="dropdown col-sm-2">
<select class="form-control" id="categories" onchange="displaySub()">
<option value="-1">-- Select Category --</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Sub-category</label>
<div class="dropdown col-sm-2">
<select class="form-control" id="sub-categories" name="category" onchange="displayFields()">
<option value="-1">-- Select Sub-category --</option>
</select>
</div>
</div>
</form>
jQuery code that is generating dynamic input fields
function displayFields(){
var cat_dropdown = document.getElementById("sub-categories");
var cat_selected = cat_dropdown.options[cat_dropdown.selectedIndex].text;
for(d of sub_cat){
if(d.text == cat_selected){
for(e of d.fields){
$("#product-form").append(`
<div class="form-group">
<label class="control-label col-sm-2" for="${e.field}" name="${e.field}">${e.field}</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="${e.field}" placeholder="Enter ${e.field}">
</div>
</div>
`)
}
$("#product-form").append(`
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button class="btn btn-default" id="add-product">Add Product</button>
</div>
</div>
`)
}
}
}
JS code for form submission
$("#product-form").submit(function(e){
e.preventDefault();
var form = $(this);
var data = form.serializeArray();
$.ajax({
url: 'http://localhost:3000/products',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(getFormData(data)),
success: function(data){
console.log("DATA POSTED SUCCESSFULLY"+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
function getFormData(data) {
var unindexed_array = data;
var indexed_array = {};
$.map(unindexed_array, function(n, i) {
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
Now, whenever I submit form only the category field is fetched. I want all the field values that are generated dynamically.
Problem is resolved. I gave name attribute to label instead of giving it to input field getting generated dynamically.
Previous code
$("#product-form").append(`
<div class="form-group">
<label class="control-label col-sm-2" for="${e.field}" name="${e.field}">${e.field}</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="${e.field}" placeholder="Enter ${e.field}">
</div>
</div>
`)
Rectified Code
$("#product-form").append(`
<div class="form-group">
<label class="control-label col-sm-2" for="${e.field}">${e.field}</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="${e.field}" name="${e.field}" placeholder="Enter ${e.field}">
</div>
</div>
`)

Optimize the repetitive code for adding new option to select jquery

Here is my fiddle : DEMO
I have repeated codes for adding new options to rule and event category select. How do I optimize the same to eliminate the repeated code?
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
Here you go - a common function helps a lot:
//Adding new category for rule
$(document).on('click', '.addrule', function() {
AddElement("categoryrule", "new-option-rule");
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
AddElement("categoryevent", "new-option-event");
});
function AddElement(selectId, newElementId){
var found = false; // Track if new value was found in list
// Loop through list options
$( "#" + selectId + " > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#" + newElementId).val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#' + newElementId).val('');
}
});
// If not found
if ($('#' + newElementId).val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#" + newElementId).val().trim();
var opt = '<option>' + val + '</option>';
$('#' + selectId).append(opt);
$('#' + selectId).val(val);
$('#' + newElementId).val('');
$("#" + selectId).click();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Here you go with some optimised code https://jsfiddle.net/3tLx884e/2/
//Adding new category for rule
$(document).on('click', '.addrule', function() {
var found = false; // Track if new value was found in list
// Loop through list options
var text = $("#new-option-rule").val().trim();
$("#categoryrule > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if (text.toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!");
found = true; // Set flag if value exists
}
if((idx + 1) === $('#categoryrule > option').length){
if ( !found && (text != '')) {
// Create new option and append to list
$('#categoryrule')
.append('<option>' + text + '</option>')
.val(text);
}
$('#new-option-rule').val('');
}
});
// If not found
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Hope this will help you.
This is my take on the problem, following jquery's slogan: "write less, do more" ...
I reduced the code further by working on local context. I. e. I only need to define one click event for everything. The click function itself figures out, what to change. It does not need any ids to do its job:
//Adding new category for rule and event
$('.form-group').on('click', 'button', addElement);
function addElement(){
var $grp=$(this).closest('.form-group'),
ival=$('input:text',$grp).val().trim(), // new input value
$sel=$('select',$grp.prev()), // select element
opts=$.makeArray($('option',$sel).map(function(i,op){
return op.textContent.toLowerCase(); }));
if ($.inArray(ival.toLowerCase(),opts)===-1){ // check existing option values
$sel.append('<option value="'+ival+'" selected>'+ival+'</option>');
}
else {alert(ival+' exists already in '+$sel[0].id);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>

Unable to dynamically add name attribute to form element

I wish to dynamically add the name attribute as 'pickup_city2' and 'pickup_address2' to select elements with ids, pickup_cityExtend and pickup_addressExtend.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cityPick form-horizontal form-label-right" action="" method="POST" novalidate>{% csrf_token %}
<div class="form-group">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="city" name="pick_up_city">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="address" name="pick_up_address">
</div>
</div>
</div>
<div class="multiCheck col-md-4 col-sm-4 col-xs-12">
<input type="checkbox" value="Yes" id="multiCheck">Have more than one pickup point?
<br>
</div>
</div>
<div class="form-group hide" id="cityPickExtend">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="pickup_cityExtend" name="">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="pickup_addressExtend" name="">
</div>
</div>
</div>
<div class="removeBtn col-md-1 col-sm-1 col-xs-2">
<button type="button" id="removeBtn">Remove</button>
</div>
<div class="addBtn">
<button type="button" id="addBtn">Add another pickup location</button>
</div>
</div>
<div class="item form-group">
<label for="shipment_datetime" class="control-label dateTime">Pickup Date & time
<span class="required">*</span>
</label>
<div class="input-group date form_datetime col-md-4 col-sm-4 col-xs-12" data-date="" data-date-format="dd MM yyyy - HH:ii p" data-link-field="dtp_input1">
<input class="form-control" size="16" name="shipment_datetime" type="text" value="" readonly style="background-color: #fff;">
<span class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</span>
<span class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</span>
</div>
</div>
</form>
Below is my jquery code.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
Within the part that you clone, there are four elements that have an id attribute. As id values must be unique, the DOM API will always return the first match when you query for a certain id, such as in these lines:
var city = document.getElementById('pickup_cityExtend');
var address = document.getElementById('pickup_addressExtend');
The results do not match the elements in the part you added to the document.
In order to make it work, you need to replace the id values with something that is unique (by adding a 2 for instance).
As a side note: you are mixing jQuery syntax with native DOM methods to retrieve elements. It would be more consistent if you would not use document.getElementById, but the jQuery $('#...') equivalent.
Here is some adjusted code:
var $clone;
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id');
// Add '2' to all ID values, and set name value to the same.
$clone.find('[id]').each(function () {
var id = $(this).attr('id') + '2';
$(this).attr('id', id).attr('name', id);
});
// Now that the id value are unique, it is OK to add the clone:
$clone.insertAfter($pick);
} else if ($clone) { // Check whether we actually have a clone
$clone.remove();
}
});

Categories

Resources