How to get the input of a selectpickers liveSearch - javascript

I have a select with 3 options and a liveSearch. If the users type an input in the liveSearch-box which doesn't exist as an option, I get the result "No results matched xy". But I want to know, what the user wrote. How do I get his input?
<body class="inventorypage" onload="selectM()">
.....
<form>
<div class="form-row">
<div class="col-lg-7">
<div class="select_box">
<select class="select4 col-md-12" single title="Auswählen" id="searchInput">
<option>Search1</option>
<option>Search2</option>
<option>Search3</option>
</select>
</div>
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
<button type="button" onclick="searchM()" class="btn3 mt-2 mb-3">Search</button>
</div>
</div>
<div class="form-row">
<div>
<p id='output'></p>
</div>
</div>
</form>
function selectM(){
var eingabe = document.getElementById('searchInput');
$(document).ready(function(){
$('.select4').selectpicker({
liveSearch: true
//,noneResultsText: 'I found no results'
});
})
}
function searchM(){
//console.log("users input");
}

The select picker creates a search input box with the class name bs-searchbox. You can get the value by following the code.
$(document).on('keyup', '.select4 .bs-searchbox input', function(e) {
alert($(this).val());
});

Related

jQuery .each through few text inputs instead of javascript .find function

I want to make validation for my input text form, that user cannot go further unless all input forms will be completed. i want to make it through every input that even if first is completed, user needs to complete another 2 etc. but at this moment i am only able to make it through the first one and have no idea how to iterate it through every input text.
My html:
<div class="write-to-us">
<div class="col-md-12 field">
<p>Write to us</p>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Name</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your Name</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Surname</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your surname</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label">Question</label>
<textarea type="text" name="subject" class="my-text-input"></textarea>
</div>
</div>
<div>
<button class="my-button">Check it</button>
</div>
</div>
And my js code for iteration:
myFunction: function() {
var $formField = $('.write-to-us');
if (!$formField.exists()) {
return;
}
initValidation();
function initValidation() {
var errorMsg = $formField.find('.label-error');
var button = $formField.find('.my-button');
var input = $formField.find('input');
var inputContainer = $formField.find('.my-form')
button.click(function(event) {
if(!input.val().trim()) {
errorMsg.css('visibility', 'visible');
inputContainer.addClass('error');
event.preventDefault();
}
});
},
I guess that problem is with .find and should be some jQuery .each but i have no idea how to change it.
I would try doing something like this rather than find.
function initValidation() {
$('.my-button').click(function(){
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my-form').addClass('error');
}
});
});
}

How do I insert Data Into database with many Input which has same name?

hello friends I have a form field in which I want to insert data which has four field which are customer_id , field_name1 ,field_name2, field_name3 ,
The question is I want to insert data which has many inputs but same input name like field_name1 field_name2 field_name3 , firstly there is no input but when I click on a button add partner details then these inputs shows by javascript .
like field_name1,field_name2,field_name3 ten times can repeat , I want to insert data in database according to there numbers with same customer_id , but different field name , below is my code , hope you understand it .
here is my code
<?php
$conn=mysqli_connect("localhost","root","","satya");
if(isset($_POST['submit'])){
$customer_id=$_POST['customer_id'];
for ($ix=0; $ix<count($_POST['field_name1']); $ix++)
{
$field_data = array(
'field_name1' => $_POST['field_name1'][$ix],
'field_name2' => $_POST['field_name2'][$ix],
'field_name3' => $_POST['field_name3'][$ix],
);
$sql="INSERT INTO customer(customer_id,details1,details2,details3) VALUES('$customer_id','$field_name1','$field_name1','$field_name1')";
$result=mysqli_query($conn,$sql);
if($result){
echo "data has been inserted";
}
else{
echo "data could not be inserted";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form action="" method="post">
<div class="form-group">
<div class="row" style="margin-top: 20px">
<div class="col-md-4" ></div>
<div class="col-md-4">
<label for="customer_id">Customer ID </label>
<input type="text" class="form-control" name="customer_id" placeholder="customer_id">
</div>
<div class="col-md-4"></div>
</div>
<div class="row" style="margin-top: 20px;">
<div class="col-md-3">
<label for="details1">details1 </label>
</div>
<div class="col-md-3">
<label for="details2">details2</label>
</div>
<div class="col-md-3">
<label for="details3">details3</label>
</div>
<div class="col-md-3">
<div>
Add Partner Details
</div>
</div>
<div class="partner_wrapper" >
</div>
</div>
<div class="col-md-4"></div>
<div class="col-md-4">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
<div class="col-md-4"></div>
</form>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
<script>
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_partner'); //Add button selector
var wrapper = $('.partner_wrapper'); //Input field wrapper
var fieldHTML = '<span class="row"><div class="col-md-3"><input type="text" class="form-control" name="field_name1[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name2[]" value=""/></div><div class="col-md-3"><input type="text" class="form-control" name="field_name3[]" value=""/></div><button type="button" href="javascript:void(0);" class="remove_button btn btn-primary" title="Remove field">Remove</button></span>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('span').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
Give the repeating fields array-style names:
<input type="text" name="field_name1[]">
PHP will collect the inputs into arrays, so $_POST['field_name1'] will be an array. Then you can loop over them:
foreach ($_POST['field_name1'] AS $index => $field1) {
$field2 = $_POST['field_name2'][$index];
$field3 = $_POST['field_name3'][$index];
// now you can insert all these values into the DB
}

jQuery incrementing a cloned elements instead of cloned div

I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
And here is the jQuery Script:
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).closest(".rounded").clone()
.insertAfter(".rounded:last")
.attr("id", "rounded" + (cloneIndex+1))
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = id.split('-')[0] +'-'+(cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parent().parent(".rounded").remove();
}
The problem is that the whole div is being cloned and just the div id is being changed:
Here is the id of each div is being incremented:
I need to clone the 2 elements only not the whole div and buttons
At the end I need t add them to database using Ajax and PHP
Here you can go with the code.
In this code i made changes in clone()
Here the changes
You first find existing child element.
Than clone that element and append it after last element
var cloneIndex = $(".clonedInput").length; this should be in clone() So it will pass proper incremented value of child element as id in your cloned html
the below code just only make clone of clonedInput not a whole div
Edit
I also edit remove function also.
It will only removes last element which was cloned.
Hope this will helps you. :)
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex+1));
}
function remove() {
$(".rounded").find(".clonedInput:last").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
You can add style to your actions class to prevent it from showing on all cloned elements
css
.actions {
display: none;
}
.clonedInput:first-child .actions {
display: block;
}
Also for the removing function you could use .closest() instead of .parent().parent()
$(this).closest(".rounded").remove();
There are a lot of things that could be optimized and replaced but I've edited your code. I believe that this is the easiest way to learn.
The edits are marked as "STACKOVERFLOW EDIT" in the comments.
$(document).ready(function() {
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
$("button.submit").on("click", submit_form); // STACKOVERFLOW EDIT: execute the submit function
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex + 1));
}
function remove() {
if($(".clonedInput").length > 1) { // STACKOVERFLOW EDIT: Make sure that you will not remove the first div (the one thet you clone)
$(".rounded").find(".clonedInput:last").remove();
} // STACKOVERFLOW EDIT
}
// STACKOVERFLOW EDIT: define the submit function to be able to sent the data
function submit_form() {
var ajax_data = $('#submit_form').serialize(); // The data of your form
$.ajax({
type: "POST",
url: 'path_to_your_script.php', // This URL should be accessable by web browser. It will proccess the form data and save it to the database.
data: ajax_data,
success: function(ajax_result){ // The result of your ajax request
alert(ajax_result); // Process the result the way you whant to
},
});
}
The HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<form action="" method="post" id="submit_form"> <!-- STACKOVERFLOW EDIT: generate a form to allow you to get the data in easy way -->
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data[]" id="diagnosis_data"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity[]" id="medication_quantity"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
</form> <!-- STACKOVERFLOW EDIT -->
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
<button class="btn btn-danger submit">Submit</button>
</div>
<!-- End class="col-sm-4" -->
</div>

Cloning a div and changing the id's of all the elements of the cloned divs

I am working with a django project, and part of the requirement is to have a button on the html page which when clicked clones a particular div and appends it to the bottom of the page as shown in the screenshot:
Screenshot of the Page
I was successful in doing this applying the following code:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find('input:text').val('') //Clear the Input fields of the cloned DIV
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:0px;clear:both"></div>
<div style="float:right">
<span class="label label-primary" id="add_cp_button" style="cursor: pointer;" onclick="addVL()">+ Add VL </span>
</div>
<div style="height:0px;clear:both"></div>
<div>
<div id="ext_int_div_1">
<div class="section">
<fieldset class="scheduler-border">
<legend class="scheduler-border">External Interface 1</legend>
<div class="sectionContent" style="border:0px solid grey;width:75%">
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Name</label>
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="vl_name_1" id="vl_name_1" placeholder="Name"/>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connectivity Type</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_connectivity_type_1" id="vl_connectivity_type_1">
<option value="VIRTIO">VIRTIO</option>
<option value="">None</option>
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connection point Ref</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_con_ref_1" id="vl_con_ref_1" />
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
</div>
</fieldset>
<div style="height:2px;clear:both;"></div>
</div>
</div>
</div>
<input type="hidden" name="vl_count" id="vl_count" value="1" />
Now i have a new issue, i need to make sure that the ID's of the elements withing the DIV are unique too, for example the the ID = "vl_name_1" for the first input box must be changed to "vl_name_2" when creating the creating the clone.
I tried the following example and added the snipped within my addVL() function just to see if any changes happen to my div's:
$("#ext_int_div_1").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + clone.id); });
However, the above code got me nothing ( i am pretty sure the above piece of code is rubbish since i have no clue what it is doing).
Help appreciated here.
Thank you
I hope the snippet below helps.
$(document).ready(function () {
$sharerCount = 1;
$('#addSharer').click(function() {
if($sharerCount < 5) {
$('#sharer_0').clone().attr('id', 'sharer_' + $sharerCount).insertAfter('.sharers:last').find("*[id]").attr('id', 'input_' + $sharerCount).val("").clone().end();
$sharerCount += 1;
}
else {
$('#addSharer').prop('disabled', 'true');
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form">
<div class="form-group">
<label class="control-label col-sm-3 col-xs-12">Share With<span class="red-text">*</span></label>
<div class="col-sm-9 col-xs-12">
<div id="sharer_0" class="field-group sharers">
<input id="input_0" type="text" class="form-control field-sm">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9 col-xs-12">
<button id="addSharer" type="button" class="btn btn-success">Add Another</button>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
I did the following and solved my problem:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find("*[id]").each(function(){
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength-1], vl_cnt);
$(this).attr('id', newId);
});
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
Thank you #ProblemChild for giving me the pointer in the right direction, I cannot upvote #ProblemChild for providing partial solution.

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

Categories

Resources