<input type="hidden" id="amenities" value="#Model.Amenities" />
<script type="text/javascript">
$(function () {
arr = new Array();
var str = document.getElementById("amenities").value;
arr = str.split(",");
for(count =0;count<arr.length;count++)
{
$("input[type=checkbox][value=arr[count]]").prop("checked",true);
}
</script>
In the model there is an attribute called "Amenities" of type string. It stores all the amenities like wifi, pool , park etc with delimiter (,). When I go to the edit page I want all those amenities to be checked which were earlier stored for that particular property.
I suggest to do it on the server when you generate the view. All you need is:
public class MyModel
{
...
public string[] Amenities { get; set; }
...
}
Then in the view:
#Html.Checkbox("WiFi", #Model.Amenities.Contains("WiFi"))
#Html.Checkbox("Pool", #Model.Amenities.Contains("Pool"))
Of course it's just an example and in real life you'll probably have a list of possible Amenities and you iterate through to render checkboxes for each of them. Also instead of strings as values I would recommend and enum.
This works:
<script type="text/javascript">
$(document).ready(function(){
var arr = $("#amenities").val().split(",");
$('input[type=checkbox]').each(function(){
if($.inArray($(this).val(), arr) >= 0){
$(this).attr("checked",true);
}
});
});
</script>
<script type="text/javascript">
$(function () {
var arr = new Array();
var str = $("#amenities").val();
arr = str.split(",");
$('input[type=checkbox]').each(function(key,val){
if(jQuery.inArray( $(this).val(), arr){
$(this).prop("checked",true);
}
})
});
</script>
Check the above code.!!
One recommendation, Since you are using jQuery, GO with jQuery syntax.
Related
I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.
How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.
What I have:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
// INSERT CODE FOR SEARCH FUNCTION
}
I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?
var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];
inputBox.onkeydown = function(evt) {
$("#autocomplete").empty();
var input, filter, a, i;
input = document.getElementById("myInput");
filter = inputBox.value.toUpperCase();
for (i = 0; i < ingredienten.length; i++) {
a = ingredienten[i];
if (a.toUpperCase().indexOf(filter) > -1) {
//console.log(a);
$("#autocomplete").append("<li>" + a + "</li>");
} else {
}
}
I think you should use the keyup event instead and you can make use of a regex and the filter function on the array of items:
var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
inputBox.onkeyup = function(evt) {
$("#autocomplete").empty();
var query = $('#ingredient').val();
// escape regex
query = query.replace(
/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
);
var queryRegExp = new RegExp('^' + query, 'i');
var results = ingredienten.filter(function(item) {
return queryRegExp.test(item);
});
results.forEach(function(item) {
$("#autocomplete").append("<li>" + item + "</li>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ingredient" />
<div id="autocomplete"></div>
Using jQuery UI autocomplete this task can be done very easily:
$('#ingredient').autocomplete({
source: ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<input id="ingredient">
Going under the instructions, you can use a regular expression filter here on your array.
const results = ingredienten.filter(item => item.match(/^ban/)); //add i at the end to ignore case
This will iterate the array and return all the results that match the regex "starts with 'ban'".
You can also do a 0-2 substring match == 'ban' but that's a bit more manual.
Guys help me with this code. The idea is to save new inputs in a string and display them using HTML. Every time I add a new one the HTML displays it, if I reload the page the items are still displayed and the first getItem method and if I reload again is still working but here is the problem. After I reload the page and I insert a new element in string then it will display the just the lates inputs and will delete the ones from other sessions.
If I insert now :"one","two","three" it I will display "one,two,three" if I reload it will still display " one,two,three" which is good, but after the reload if I insert "four" it will display only "four" and I want to be displayed "one,two,three,four".
How can I make this happen?
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<button onclick="reloadd()">Reload</button>
<button onclick="clearF()">Clear</button>
<input id="valoare">
<button id="adauga" onclick="adauga()">+</button>
<button onclick="nrElemente()">ElemNr?</button>
<script>
var cars = [];
var two = "kes";
document.getElementById("result").innerHTML = localStorage.getItem("array1");
function clearF() {
window.localStorage.clear();
location.reload();
}
function adauga() {
var x = document.getElementById('valoare').value;
cars.push(x);
localStorage.setItem("array1", cars);
document.getElementById("result").innerHTML = localStorage.getItem("array1");
}
function reloadd() {
location.reload();
}
function nrElemente() {
alert(localStorage.length);
}
</script>
</body>
</html>
Your code is not working because you are not storing your array anywhere.
To save your array into localStorage you would use:
localStorage.setItem("cars", JSON.stringify(cars));
Then instead of doing this:
var cars = [];
You would load your cars array like this:
var cars = localStorage.getItem("cars");
cars = (cars) ? JSON.parse(cars) : [];
What this is doing is, it is checking if the localStorage object contains an array called cars. Now if it does it will parse that string and return the stored cars array, if it does not it will set the cars array to a new empty array.
Here, I have fixed and tidied your code:
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<button onclick="reloadd()">Reload</button>
<button onclick="clearF()">Clear</button>
<input id="valoare" />
<button id="adauga" onclick="adauga()">+</button>
<button onclick="nrElemente()">ElemNr?</button>
<script type="text/javascript">
var array1 = localStorage.getItem("array1");
array1 = (array1) ? JSON.parse(array1) : [];
var two = "kes";
document.getElementById("result").innerHTML = localStorage.getItem("array1");
function clearF() {
window.localStorage.clear();
location.reload();
}
function adauga() {
var x = document.getElementById("valoare").value;
array1.push(x);
localStorage.setItem("array1", JSON.stringify(array1));
document.getElementById("result").innerHTML = localStorage.getItem("array1");
}
function reloadd() {
location.reload();
}
function nrElemente() {
alert(localStorage.length);
}
</script>
</body>
</html>
Also, it's considered bad practice to place your JavaScript events & functions in HTML attributes. Try to separate HTML, CSS & JS as much as possible by placing all (or at-least most) of your JS in your script element / JS file.
Good luck and all the best.
You are creating an empty array every page load and when you add to array you store that but never connect cars array to the data that is already stored
Try changing
var cars =[];
To
var localData = localStorage.getItem("array1");
// if localData not undefined then parse that as cars array, otherwise is empty array
var cars = localData ? JSON.parse(localData) : [];
When you go to store the cars array change to:
localStorage.setItem("array1",JSON.stringify(cars));
There were some major issues with your code, this is a fixed version:
<script type="text/javascript">
var cars = [];
try {
cars = JSON.parse(localStorage.getItem("array1"));
} catch (err) {}
var two = "kes";
document.getElementById("result").innerHTML = cars;
function clearF() {
window.localStorage.clear();
location.reload();
}
function adauga() {
var x = document.getElementById('valoare').value;
cars.push(x);
localStorage.setItem("array1", JSON.stringify(cars));
document.getElementById("result").innerHTML = localStorage.getItem("array1");
}
function reloadd() {
location.reload();
}
function nrElemente() {
alert(localStorage.length);
}
</script>
I am new to javascript and I can't populate many fields with one click.
<script>
function addTxt(txt, field)
{
var myTxt = txt;
var id = field;
document.getElementById(id).value = myTxt;
}
</script>
<input type="text" name="xx" id="info" autofocus="required">
<p>x</p>
I've got 3 more fields.
Thanks.
You can use
function addTxt(txt, ids)
{
for (var i=0, l=ids.length; i<l; ++i) {
document.getElementById(ids[i]).value = txt;
}
}
And call it like
addTxt('Some text', ['id1', 'id2', 'id3']);
You can populate multiple fields. I have shared a jsfiddle link. You can populate multiple fields using this code.
function addTxt(_val, _id,_no)
{
var _myTxt = _val;
var _id = _id;
for(var i=1;i<=_no;i++){
document.getElementById(_id+i).value = _myTxt;
}
}
Click here to see DEMO
I think you don't need a function to do this.
Just use
document.getElementById('id1').value
= document.getElementById('id2').value
= document.getElementById('id3').value
= 'Some text';
Or, if you think document.getElementById is too long, use a shortcut:
var get = document.getElementById;
/* ... */
get('id1').value = get('id2').value = get('id3').value = 'Some text';
Try getting the elements by tagName or by className instead of by id, then using a for loop to iterate through each one.
Q1: My point is create many buttons as many rows of array. Like this, only one button appears.
<script type="text/javascript">
var myArray = [];
$('#button').click(function(){
var value1 = $('#value1').val();
var value2 = $('#value1').val();
var value3 = $('#value1').val();
var newArray = [];
var newArray[0] = value1;
var newArray[1] = value2;
var newArray[2] = value3;
myArray.push(newArray);
$("#save").append(
$("<button>").click(function() {
myFunction.apply(null, myArray);
}).text("Click me!")
);
});
});
function myFunction(value1,value2,value3)
{
var jsonData = $.ajax({
url: "file.php?value1=" + value1 + "&value2=" + value2 + "&value3=" + value3
dataType: "json",
async: false
}).responseText;
(...)
}
//edited: problem maybe found. I said buttons dont do anything because of this.
OUTPUT: file.php?value1=paul,23,USA&value2=undefined&value3=undefined
//it seems that value1 gets all values :s
</script>
<div id ="save"></div>
Im looking for a solution that return someting like this:
eg:
<!--<button onclick="myFunction(name,age,country)">Click me</button>-->
<button onclick="myFunction(paul,23,USA)">Click me</button>
<button onclick="myFunction(john,23,USA)">Click me</button>
EDITED MY CODE WITH MORE DETAILS
.html replaces, and your quotes are mismatched. But it doesn't matter - jQuery is better at manipulating the DOM than it is at manipulating strings. Try:
$("#save").append(
$.map(myArray, function(item) {
return $("<button>").click(function() {
myFunction.apply(null, item);
}).text("Click me");
})
);
Here's a demo.
You're only seeing one button because the .html() method replaces the html of the element. It doesn't append.
Luckily, jQuery has a method for the behavior you want, fittingly called append. Change it to look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>");
$("#save").append(button) ;
}
I intentionally left the onclick behavior out of that snippet. You can write it in the html of the button you create, as you have been, or you can do it with jQuery - the second method is preferable, and would look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>")
.click(function(){
// call the actual function you want called here
});
$("#save").append(button);
}
Did you mean this:
<div id="save">
</div>
<script type="text/javascript">
function addButtons(){
for(i=0;i<myArray.length;i++)
{
var button = $('<button id="btn_'+i+'" onclick="myFunction(this);">Click me</button>')
$(button).data('details',myArray[i]).appendTo("#save");
}
}
function myFunction(element){
alert($(element).data('details'));
}
</script>
This is because you are replacing the html in the $("#save") in the loop . Try
$("#save").append("<button onclick="myFunction('"+myArray[i]+"')">Click me</button>") ;
for(i=0;i<myArray.length;i++){
//Create a new DOM button element ( as jQuery object )
// Set the current button index, and add the click action
var button = $('<button />').data('myindex', i).click(function(){
var myArrayItem = myArray[$(this).data('myindex')];
alert(myArrayItem);
}).html('My label n. '+i);
$('#save').append(button)
}
Why bothering with all the JQuery and complicated code, just use simple way to implement this
<script type="text/javascript" >
var myArray = ["New York", "Boston", "San Jose", "Los Angeles"];
var strHTML = "";
for(i=0;i<myArray.length;i++)
{
strHTML += "<button onclick='myFunction("+i+")'>Click me</button>";
}
$("#save").innerHTML = strHTML;
function myFunction(index)
{
alert(index);
// do your logic here with index
}
</script>
I have project that concerns about calendars, at first i have 1 calendar and now i want to have another one but they have different values.
<div id="cal">
....
</div>
<div id="calq">
....
</div>
my question is, how can I check if div id is "calq" in javascript?
if div.id == "calq" ?
...
at first i have ...
<script type="text/javascript">
monthYear = Date.today();
var cal = new Calendar();
cal.generateHTML();
$('#cal').html(cal.getHTML());
setMonthPrice();
setSpecialPrice()
</script>
then i added
<script type="text/javascript">
monthYear = Date.today();
var calq = new Calendar();
calq.generateHTML();
$('#calq').html(calq.getHTML());
setMonthQuantity();
setSpecialQuantity();
</script>
but the setMonthQuantity() also called by cal, i just want the setMonthQuantity() only for calq
function setMonthQuantity()
{
var weekdayBaseQuantity;
weekdayBaseQuantity = {{ product.quantity }};
$('td.calendar-day').append('<div class="dayquantity">' + weekdayBaseQuantity + '</div>');
$('td.Sat .dayquantity, td.Sun .dayquantity').text( weekdayBaseQuantity );
}
To determine the existence, in clean javascript
if(document.getElementById("calq")!='undefined')
{
// do something, it exists
}
using jquery
if($("#calq").length)
{
// do something, it exists
}
To check the id, in clean javascript
if(this.getAttribute('id')=="calc")
{
// do something, it exists
}
Using jquery
if($(this).attr("id")=="calq")
{
// do something, it exists
}
You can do check it, for example, via Jquery. I suppose that you want to make something like switch and for each div do some operation. If I'm right you can use Jquery's each function for looping against div elements and following condition for checking id's.
if($(this).attr("id")=="calq")
Here you go:
if ($('#calq').length === 1) {
// there is id = calq
}
Seems like the best solution would be to pass in the div to the functions you are calling. That way you know the div you are dealing with.
eg.
<script type="text/javascript">
monthYear = Date.today();
var cal = new Calendar();
cal.generateHTML();
var calDiv = $('#cal');
calDiv.html(cal.getHTML());
setMonthPrice(calDiv);
setSpecialPrice(calDiv)
</script>
<script type="text/javascript">
monthYear = Date.today();
var calq = new Calendar();
var calqDiv = $('#cal');
calqDiv.html(cal.getHTML());
setMonthQuantity(calqDiv);
setSpecialQuantity(calqDiv);
</script>
I am assuming the $('td.calendar-day') is in the calendar HTML? If so setMonthQuantity would be something like
function setMonthQuantity(calDiv)
{
var weekdayBaseQuantity;
weekdayBaseQuantity = {{ product.quantity }};
calDiv.closest('td.calendar-day').append('<div class="dayquantity">' + weekdayBaseQuantity + '</div>');
calDiv.closest('td.Sat .dayquantity, td.Sun .dayquantity').text( weekdayBaseQuantity );
}