Error duplicating Div with Select2 library - javascript

I am trying to clone a div, which contains some input, and one of those is the Select2 library, when cloning it clones me but the library does not work.
attached bug: "Uncaught TypeError: Cannot set properties of null (setting 'outerHTML')".
This is my html code.
<div class="cloned" style="width: 100%;">
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="txtinput0" name="username" placeholder="Enter Full Name" type="text" data-parsley-pattern="^[a-zA-Z\s.]+$" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="txtinput0" name="email" placeholder="Enter VALID EMAIL and check the result" type="email" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="txtinput0" name="phone" placeholder="Enter Phone e.g.: +363012345" type="text" data-parsley-pattern="^\+{1}[0-9]+$"/>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<select class="chosen-select" multiple="multiple" style="width: 100%;" id="select0" data-placeholder="Select a company" >
<div clas="options">
<option value="1">Google</option>
<option value="1">Amazon</option>
<option value="1">Facebook</option>
<option value="1">Airbnb</option>
</div>
</select>
</div>
</div>
</div>
</div>
<div clas="row box" id="clone"></div>
And this is the javascript with which I try to clone the whole div, including the select2
$(document).ready(function() {
$('#select0').select2();
});
var i=1;
var prev =0;
function addRow() {
var clone = $("#row_examenes").clone()
clone.find("#txtinput"+prev).attr("id", "txtinput"+i);
clone.find("#select"+prev).attr("id", "select"+i);
clone.find("#select"+prev+"_chosen").attr("id", "select"+i+"_chosen1");
clone.appendTo($("#clone"));
document.getElementById("select"+i+"_chosen1").outerHTML=""
$myid = $('#select' + i);
$myid.show().select2();
i++;
prev++;
}

There are quite a few problems in the code, but the big issue is:
When you initialise a Select2, it hides the original <select> and adds some extra HTML on the page. If you then clone the block of HTML where that Select2 is, you clone all that extra Select2 stuff. And if you then try an initialise that cloned stuff as a Select2, it won't work.
The fix is described in many duplicate questions here on SO already (try searching for "select2 clone"), here's an example: you need to destroy the original Select2 before cloning it, and then re-initialise it as a Select2 again once it is cloned;
Some of the other issues in the code are:
There is no element with id row_examenes. I added it as a <div> enclosing the <div class="cloned">;
Once you clone that div, the clone will have the same ID (row_examenes), and the code does not change that ... duplicate IDs are invalid HTML. Instead we can clone the <div> nested inside, with class cloned;
All 3x text <input>s have the same ID, txtinput0 - this is invalid, and jQuery will only be able to find the first one. I changed them to name0, email0, and phone0;
The HTML has an unbalanced </div>, the opening <div> I added fixes that too;
After the clone is created, and before the IDs are updated, it includes elements with non-unique IDs. It isn't actually in the DOM yet, and you are using clone.find() to scope your search to find them, so probably that's OK ...? But it seems unnecessarily risky, when we don't have to do it that way - why not play it safe, and search for the inputs instead of the IDs;
<div clas="row box" id="clone"></div> - typo in class;
There was no way to trigger addRow() so I added a simple button, and a click handler for it;
Here's a working, simplified snippet with those issues fixed:
$(document).ready(function () {
$('#select0').select2();
$('button').on('click', addRow);
});
// How many clones on the page?
let clones = 0;
function addRow() {
// We've added a clone
clones++;
// First need to destroy original select2, so the clone does not include
// extra stuff select2 generates.
$('#select0').select2('destroy');
// Now create our clone
let clone = $("#row_examenes .cloned").clone()
clone.find('input[name="username"]').attr("id", "name" + clones);
clone.find('input[name="email"]').attr("id", "email" + clones);
clone.find('input[name="phone"]').attr("id", "phone" + clones);
clone.find("select").attr("id", "select" + clones);
// HTML is updated, add it to the DOM
clone.appendTo($("#clone"));
// Reinitialise the original select2
$('#select0').select2();
// And initialise our new select2
$('#select' + clones).select2();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<button>Create a clone</button>
<div id="row_examenes">
<div class="cloned">
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="name0" name="username" placeholder="Enter Full Name" type="text" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="email0" name="email" placeholder="Enter VALID EMAIL and check the result" type="email" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<input class="form-control" id="phone0" name="phone" placeholder="Enter Phone e.g.: +363012345" type="text" />
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
<select class="chosen-select" multiple="multiple" id="select0" >
<div clas="options">
<option value="1">Google</option>
<option value="1">Amazon</option>
<option value="1">Facebook</option>
<option value="1">Airbnb</option>
</div>
</select>
</div>
</div>
</div>
</div>
<div class="row box" id="clone"></div>

Related

How to load the value of a drop down to a text box when selected

I am working on a front end project and have a set of Dropdown list where it can be selected.
My requirement is when I select a specific dropdown name the corresponding value of it has to load in the next text box.
This is the code that I tried.
$('#selseriessetupid').change(function(){
var employeenumber = $(':selected',this).data('lastused');
$('.form-control').val(employeenumber);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-3 col-lg-3 col-xs-3 col-sm-3 uiblock">
<div class="form-group uicontrol editControl" data-displaytype="dropdownlist" data-fieldname="seriessetupid" data-templateitemid="8875">
<label class="clsCaption">Employee Number</label>
<select class="form-control" name="seriessetupid" id="selseriessetupid">
<option value="0">Please select Status</option>
<option data-lastused="01" value="126">FIN1</option>
<option data-lastused="01" value="124">FIN</option>
<option data-lastused="01" value="125">CRM</option></select></div>
</div>
<div class="col-md-3 col-lg-3 col-xs-3 col-sm-3 uiblock">
<div class="form-group uicontrol editControl" data-displaytype="textbox" data-fieldname="employeenumber" data-templateitemid="8796">
<label class="clsCaption">Employee ID</label>
<input type="text" placeholder="Employee ID" class="form-control " name="employeenumber" id="employeenumber">
</div>
</div>
</div>
You can get the value of Select dropdown (#selseriessetupid) using .val() function of jquery and try setting it in the #employeenumber value.
$(document).ready(function() {$('#selseriessetupid').change(function(){
$('#employeenumber').val($('#selseriessetupid').val());
});
});
You have to use the next() method of Jquery. Try this one
$('#selseriessetupid').change(function(){
var employeenumber = $(':selected',this).data('lastused');
$(this).next('.form-control').val(employeenumber);
});
Note It will not work in all situations cause your are using an ID selector. change it to class to work properly.

Form in HTML with button assigns the value of the last button, no matter which one was selected

I want to create a form with HTML with different types of inputs (such as name, surname, dates, and radio-button options), and when I want to print the object with the data inputted in the form on the console, the value from the radio-buttons is not stored correctly.
First of all, this is my first project on this area and also my first posted question on stackoverflow, so I would appreciate some suggestions on how to pose the question better if I'm forgetting some crucial data.
I have been following help from different resources (mostly youtube videos such as: https://www.youtube.com/watch?v=GrycH6F-ksY ) to create this form and submit the data with AJAX, and the code of my javascript application comes mainly from that video.
All the data is stored correctly and I can see it in the console, except from the data comming from the radio-buttons. No matter what option is selected (either "male" or "female"), the console always shows the value of the last button, which in this case is "female". I suppose I am doing something wrong when defining these buttons, and why they are not being "selected" (I suppose that's what is happening since the data shown is always the last default value) but I haven't been able to find out where I am doing something wrong.
I'm including the part of the code that I think might be relevant
<form action="ajax/contact.php" method="post" class="ajax">
<div class="form-row">
<div class="form-group col-md-6">
<label>Name</label>
<input type="text" class="form-control" name="inputName" required>
</div>
<div class="form-group col-md-6">
<label>Surname</label>
<input type="text" class="form-control" name="inputSurname" required>
</div>
</div>
<div class="form-group">
<label>Date of birth</label>
<input type="date" class="form-control" name="inputDate">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="inputEmail" required>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>Gender</label>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="male">Male</div>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="female">Female</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Number of children</label>
</div>
<div class="form-group col-md-6">
<input type="number" class="form-control" name="inputNumber">
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Javascript function
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
return false;
});
PHP file
<?php
if (isset($_POST['inputName'],$_POST['inputSurname'],$_POST['inputDate'],$_POST['inputEmail'],$_POST['inputGender'],$_POST['inputNumber'])) {
print_r($_POST);
}
In the console I'm getting this:
${inputName: "myName", inputSurname: "mySurname", inputDate: "2019-12-13",
$inputEmail: "myMail#gmail.com", inputGender: "female", …}
$inputDate: "2019-12-13"
$inputEmail: "myMail#gmail.com"
$inputGender: "female"
$inputName: "myName"
$inputNumber: "1"
$inputSurname: "mySurname"
$_proto_: Object
but I thought it would be showing:
$...
$inputGender: "male"
$...
when the male option is selected.
Thank you very much
The problem is in your JS. You're looping through everything with a name attribute, in order, and adding its value to your submit data. In the case of radio buttons, you have to check if they're selected and only add if so, otherwise, the last one always wins, as you're seeing.
And since you appear to be using jQuery, you can probably just let its serialize helper do this work for you.

Javascript Hide-Unhide HTML Text Box

I want to hide & un-hide html text box when selecting another select value using JavaScript.
$(document).on('change', '#pf_status', function() {
var val = $(this).val();
console.log(val);
if (val == 2) {
$('#ref-col').hide();
} else {
$('#ref-col').show();
}
});
$(document).ready(function() {
$('#ref-col').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group">
<label>
Pass Fail Status <span class="text-danger">*</span>
</label>
<select class="form-control" name="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group">
<label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>
I did not get the desired output. I think something going wrong. Can any one help me ?
Spelling the selector the same as the ID
ID not name is used in the script
No need to delegate if not dynamic
Dropdown does not have a "please select" so trigger the change on load of the page
$(function() {
$('#pf_status').on('change',function() {
var val = $(this).val();
$('#ref_col').toggle(val != 2);
}).trigger("change"); // trigger to handle the lack of "Please select"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group">
<label>
Pass Fail Status <span class="text-danger">*</span>
</label>
<select class="form-control" id="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group">
<label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>
This is an issue with your selector you are selecting the drop-down with a name using a # sign:
and there's also a problem with your selector #ref-col in your JS it should be like this #ref_col
change your name to id="pf_status" in your HTML like this and this will work:
$(document).on('change', '#pf_status', function() {
var val = $(this).val();
$('#ref_col').toggle(val!=2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group">
<label>
Pass Fail Status
<span class="text-danger">*</span>
</label>
<select class="form-control" id="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group">
<label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>
You should always try to figure out why the code it is not working.
Always check your browser console, There you will get errors with line numbers.
This way you will learn to master coding with time.
And don't worry about negative rating for your question.WE are developers to push ourselves to create, develop and design for the betterment of the world.
JQUERY:
$(document).on('change','#pf_status',function(){
// Here you are using this object to refer to something that is not available in DOM.
});
In your HTML, use id attribute for the select element.And this will work fine.
Well that is already shown above.I will show you how to setAttribute in javascript for your code without changing any code in your HTML.So that you learn.
In Javascript:
let ps = document.getElementsByName('pf_status');
ps[0].setAttribute("id","pf_status"); // if you have only 1 select element in your document
There surely are other issues in your code that are all sorted out by other developers.
You are using ID selector in your JQuery and declared as name attribute in your form
<select class="form-control" name="pf_status">
either change it to <select class="form-control" id="pf_status">
or
Use the name selector $(document).on('change', 'select[name="pf_status"]' in JQuery selector.
$(document).on('change', '#pf_status', function() {
var val = $(this).val();
console.log(val);
$('#ref_col').toggle(val!= 2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="form-group"><label>Pass Fail Status <span
class="text-danger">*</span></label>
<select class="form-control" id="pf_status">
<option value="1">Pass</option>
<option value="2">Fail</option>
</select>
</div>
</div>
<div class="col-md-3" id="ref_col">
<div class="form-group"><label>Pass Date</label>
<font style="font-size: 14px; color: #AA0000"></font>
<input type="text" name="pass_date" id="pass_date" class="form-control" value="somedate">
</div>
</div>

setting only the input field as empty string without the selection tag

I have a container that consists of a couple of inputs tag and one select tag. All of them have className, let's call it "contact". In jquery , I am accessing all of them through "contact". Also, there is checkbox that disables when you check it and when toy uncheck it, it empties the input fields and remove disable . The thing i want to do I want when i uncheck the checkbox, I want to set the the input fields as empty string, which i did, but what i did include the selection tag which i do not set as empty string
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").val("");
}
});
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10 contact">
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
There is error but i dont know what is it
Include the $ reference in your code. That means add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
in your html
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").each(function(i, el){
if($(el)[0].nodeName != "SELECT"){
$(el).val("");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10 contact">
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
</div>
Sorry, I don't have enough reputation to comment.
I tested your code and that works well as you want.
You missed selecting jquery in stackoverflow code snippet.
please check follow code.
If it's not working even after you added jquery script, then please let me know jquery version you used. (don't forget to add jquery cdn or picking jquery library in code snippet editor)
if you want to keep selection of select element please remove the contact class in there like below.
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10"> <!-- I removed contact class in here to keep selection -->
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>

Load bootstrap forms from select page

I have a register form. I just need to load bootstrap form in same page behind the select menu when someone click something from select menu. Should I hide form until someone click that item in select menu right?
This is my code.
<div class="form-group">
<select class="form-control menu">
<option>Select category*</option>
<option>Apartment</option>
<option>Lands</option>
</select>
</div>
I need to load this form someone click Apartment in the menu.
<form>
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="Size(sqft)">
/div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="No of bedrooms">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" placeholder="No of bathrooms">
</div>
</div>
</div>
</div>
</form>
I tried play with this code. But it redirect to another pages.
<script>
$('select.menu').change(function(e){
// this function runs when a user selects an option from a <select> element
window.location.href = $("select.menu option:selected").attr('value');
});
</script>
What method do I need to follow?
Have a look at this jsfiddle:
I gave your wrapper of your apartment an id <div class="col-md-12" id="apartment">.
So I added following jQuery to toggle your html of your apartment:
$('select.menu').change(function(){
// this function runs when a user selects an option from a <select> element
switch($(this).find("option:selected").prop('value')) {
case '1': $('#apartment').show(); break;
default: $('#apartment').hide(); break;
}
});
And don't forget to hide your #apartment:
#apartment {
display: none;
}
window.location.href will redirect you to the new page. You can just hide your form before user make a select change or get it dynamically with jQuery.load() function.
Let's say your HTML,
<div class="form-group">
<select class="form-control menu">
<option>Select category*</option>
<option>Apartment</option>
<option>Lands</option>
</select>
</div>
by default let the form is in display:none.
Jquery,
<script>
$('select.menu').change(function(e){
// this function runs when a user selects an option from a <select> element
window.location.href = $("select.menu option:selected").attr('value');
if($(this).val == "Apartment"){
$('form').show();
}else{
$('form').hide();
}
});
</script>

Categories

Resources