Create fields dynamically in js - javascript

I create dynamic inputs and selects in js by clicking the button.
To fill in the select, I query a table in the database. The problem I have is that whenever I click the button to create a new input and select, it clears the previous select and shouldn't.
Code:
var cars = [
{colour: "red", },
{colour: "white", },
{colour: "black", },
];
var campos_max = 10;
var x = 0;
$('#add_field').click (function(e) {
e.preventDefault();
if (x < campos_max) {
$('#listas').append('<select class="form-control1 Reff" name="Ref[]"></select>');
}
var html = $('.Reff').html("");
cars.forEach(element => {
html += `<option value="`+element.colour+`">`+element.colour+`</option>`;
});
$('.Reff').html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listas"></div>
<button type="button" id="add_field" class="btn btn-warning caixa"><span class="material-icons">add</span></button>
I intended that when clicking the button to create a new select and input, do not delete the value that I already placed in the previous select.
The problem is that it always queries the database and then returns the data back to the previous select, but I don't know how to solve it.
Can anyone help?

Related

Display another button with autocomplete in JS

I'm tring to do a autocomplete from json url, it works good.
Now what I want, it's when I click to the autocomplete, I want to display the import button and if input is empty or we put a new value (not in the import), display the create button.
Give you a example on what i'm doing with some datas:
$('#search-deal').autocomplete({
source: function(request, response) {
var data =[{
"id": 1671,
"title": "Queens Park Tyres deal"
}, {
"id": 1672,
"title": "Wildman Craft Lager deal"
}, {
"id": 1673,
"title": "General Store deal"
}, {
"id": 1674,
"title": "Deluxe Off Licence deal"
}, {
"id": 1675,
"title": "Ahmed Halal Bazaar deal"
}];
var datamap = data.map(function(i) {
return {
label: i.id + ' - ' + i.title,
value: i.id + ' - ' + i.title,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
if(i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0){
document.getElementById("create").style.visibility = 'hidden';
document.getElementById("import").style.visibility = 'visible';
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
};
});
response(datamap);
},
minLength: 1,
delay: 100
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="text" id="search-deal" />
<button id="create" type="submit" class="btn btn-primary">Créer une affaire</button>
<button id="import" type="submit" style="visibility:hidden" class="btn btn-primary">Importer</button>
The problem here, it's when I write "p", the button import show up and I want to show up only when I click to the autocomplete.
The second problem, it's the button create nevere come back if value is empty or put another value
Anybody can help me ?
I understand from the shared snippet that you are using jquery ui autocomplete.
I would suggest following changes/updates to your code
For changing button display on selecting the autocomplete item, use select event. https://api.jqueryui.com/autocomplete/#event-select
Whenever user types something, hide the import button. Display it only when an item is selected.
For handling empty input case, use oninput event.
I have made following changes to the code you shared
Added a new function to handle button toggle
Hide the import button from source property i.e. when user type some input and also when input box is blank
Show the import button when user selects an autocomplete option
Working code link: https://plnkr.co/edit/PgzUuOADhIqk9zbl?preview
I hope this solves your issue

Is it possible to make a text input with suggestions based on what you type?

How would I go about having a drop down appear based off of what I type into a text field, where the selected option would 'write' itself into the text field? For example if I was asked what my favourite colour was and I began by typing 'dar' a dropdown would appear with options 'dark red', 'dark blue', 'dark green' etc. however if I typed in 'dark g' a dropdown would appear with only the option 'dark green'? Think of it kind of like a text input that eliminates choices off a dropdown, however selecting an option in the dropdown inputs them into the text field.
This is my code at the moment (although I assume I'll need JS?):
<input type="text" placeholder="Name Of Gear">
<input type="number" class="amount" maxlength="4" placeholder="Amount" max="999">
If you want to autocomplete a entire dictionary, this is to slow.
But if you just want to autocomplete some words (like "green", "red", etc.) this should do it.
In your HMTL you need a input and a div.
The input is for typing and the div presents the suggestions.
<input id="input" oninput="findSuggestions('input', 'suggestions')">
<div id="suggestions"></div>
So if you type, a function will be called.
This function will go through an array with all the suggestions in it.
var arySuggestions = ["Alarm", "Already" , "Ballon"] // This is where all you suggestions go
function findSuggestions(strInputId, strSuggestionsDivId) {
var objInput = document.getElementById(strInputId)
var strInput = objInput.value // get the current text
var objSuggestionsDiv = document.getElementById(strSuggestionsDivId)
if (strInput.length > 0) {
objSuggestionsDiv.innerHTML = ""; // empty the suggestion div, just in case
var objList = document.createElement("ul");
for (var i = 0; i < arySuggestions.length; i++) {
var word = arySuggestions[i]
var wordPart = word.substring(0,strInput.length)
if (word.length > strInput.length && wordPart === strInput) { // check if the words are matching
// if they do create a list entry
var objListEntity = document.createElement("li");
objListEntity.setAttribute("onclick", "complete('" + word + "', '" + strInputId + "', '" + strSuggestionsDivId + "');");
objListEntity.innerHTML = word;
objList.appendChild(objListEntity);
}
}
// show the suggestionList
objSuggestionsDiv.appendChild(objList);
} else {
objSuggestionsDiv.innerHTML = ""; // empty the suggestion div
}
}
And there is a second function. So that when you click on the suggestion it will fill it in:
function complete(strComplete, strInputId, strSuggestionsDivId) {
document.getElementById(strInputId).value = strComplete;
document.getElementById(strSuggestionsDivId).innerHTML = ""; // empty the suggestion div
}
If you want the suggestions to follow your cursor you will probably need some css.
Hope this helps

Why does jQuery dropdown require two clicks?

When I click on the button labeled "Continents & Oceans," a dropdown list appears - but only if I click on the button twice. I'd like it to work with the first click.
Is there something wrong with my code, or do I need to add something to make the dropdown drop down on the first click?
This is a jQuery function, but it also includes my first experiment with AJAX, so maybe that's the problem.
<input type = "button" id = "konoce" value = "Continents & Oceans" class="btn btn-konoce"
<div id = "div-konoce"> </div>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#konoce").click(function(event) {
if ($('#div-konoce').html() == '') {
$.get( "/2b/inc/ajax/db-lists/world/konoce.php", { name: "KonOce" }, function(data) {
$('#div-konoce').html(data);
});
}
else {
$('#div-konoce').html('');
}
});
});
</script>
EDIT:
I revised my code per the answer below. However, it still takes two clicks to open the dropdown.
<button type = "button" id = "konoce" class="btn btn-konoce">Continents & Oceans</button>
<div id = "div-konoce" style="margin: 0 -5px;"> </div>
Your line:
if ($('#div-konoce').html() == '')
checks if the "div-konoce" div is empty, but it's not:
<div id = "div-konoce"> </div>
There's a space there... meaning not == ''
Remove the space and try again.
you are not closing your input - it should be:
<input type = "button" id = "konoce" value = "Continents & Oceans" class="btn btn-konoce" />
and I am not sure why you have this as an input and not a button, since it not used to gather information - but acts as a trigger fo the click.:
<button type = "button" id = "konoce" class="btn btn-konoce">Continents & Oceans</button>
One tip is ,Why are you always emptying $('#div-konoce') , it will cause one ajax request per click . But if you only wrote the first if , it will show the previously loaded menu after the first click onwards .
<div id = "div-konoce"></div>
if ($('#div-konoce').html()=='') {
$.get( "/2b/inc/ajax/db-lists/world/konoce.php", { name: "KonOce" }, function(data) {
$('#div-konoce').html(data);
});

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

Add edit/delete button at the end of the table row

I've inline create of row in table in my index view.when user click on add row button it pre-append new editable row to the table .
at the end of the row there is button for save the data of the new row.when user click on save I disable the textboxes and checkboxes and
remove the button of create, what I need is instead add to this row the button of edit and delete, which is default for all table rows, how should I do that?
Here is the code for disable the row fields:
//Hide the create button
$('#btnsubmit').remove();
//Change the name property to disabled
$('input').attr('readonly', true);
$('#name').css("border", "none");
Here is the defult button for all the rows(if i press on create and refresh the page I will see the button also in this new saved row but I want to
add them when the row is added and the page was not refreshed...
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
This is how I add the new row with the create button when user click on create new row
var html = '<tr><td>#Html.TextBox("name")</td><td>#Html.CheckBox("checkBox1")</td><td>#Html.CheckBox("checkBox2")</td><td>#Html.CheckBox("checkBox3")</td><td><input id="btnsubmit" type="submit" value="Create" class="btn btn-default" /></td><td></tr>';
function addRow() {
if ($('#btnsubmit').length == 0) {
//Append new row to the table
jQuery(html).prependTo('#data-table');
UPDATE
this is the example of the table which for every row there is edit/delete button
UPDATE 2
I try to add the following but the button is not added when click on create
$('#btnsubmit').click(function () {
$.post("/Roles/Create", { name : $("name").val() }, function(NewID){
var oTD = $("#btnsubmit").parent();
oTD.append("<a href='/Roles/Edit/"+ NewID +"'>Edit</a>");
oTD.append("<a href='/Roles/Delete/"+ NewID +"'>Delete</a>");
});
You will have to return the ID in response of ajax call and add append anchor with the returned ID
function SaveData()
{
$.post("/[Controllar]/Savedata", { firstname : $("txtFirst").val(), lastname : $("txtLast").val() }, function(NewID){
var oTD = $("#btnsubmit").parent();
oTD.append("<a href='/[ControllarName]/Edit/"+ NewID +"'>Edit</a>");
oTD.append("<a href='/[ControllarName]/Detail/"+ NewID +"'>Detail</a>");
oTD.append("<a href='/[ControllarName]/Delete/"+ NewID +"'>Delete</a>");
//Hide the create button
$('#btnsubmit').remove();
//Change the name property to disabled
$('input').attr('readonly', true);
$('#name').css("border", "none");
});
}

Categories