Automatically get values of all element inside a div with jQuery - javascript

I have a main div and inside of this, there are a lot of input text and radio button.
Like this:
<div id="mainDiv">
<input type="text" name="text-1" /> <br/>
<input type="radio" name="radio-1" />Yes
<input type="radio" name="radio-1" />No <br/>
<input type="text" name="text-2" /> <br/>
<input type="text" name="text-3" /> <br/>
</div>
<img src="img/img.gif" onclick="getAllValues();" />
I want to define the function getAllValues() in jQuery to get all values in mainDiv and save them in a string.
It is possible?

To achieve this you can select all the form fields and use map() to create an array from their values, which can be retrieved based on their type. Try this:
function getAllValues() {
var inputValues = $('#mainDiv :input').map(function() {
var type = $(this).prop("type");
// checked radios/checkboxes
if ((type == "checkbox" || type == "radio") && this.checked) {
return $(this).val();
}
// all other fields, except buttons
else if (type != "button" && type != "submit") {
return $(this).val();
}
})
return inputValues.join(',');
}
The if statement could be joined together here, but I left them separate for clarity.

Try something like that:
function getAllValues() {
var allVal = '';
$("#mainDiv > input").each(function() {
allVal += '&' + $(this).attr('name') + '=' + $(this).val();
});
alert(allVal);
}

Here is solution which is building you a JSON string. It's getting the values of the text fields, check boxes and select elements:
function buildRequestStringData(form) {
var select = form.find('select'),
input = form.find('input'),
requestString = '{';
for (var i = 0; i < select.length; i++) {
requestString += '"' + $(select[i]).attr('name') + '": "' +$(select[i]).val() + '",';
}
if (select.length > 0) {
requestString = requestString.substring(0, requestString.length - 1);
}
for (var i = 0; i < input.length; i++) {
if ($(input[i]).attr('type') !== 'checkbox') {
requestString += '"' + $(input[i]).attr('name') + '":"' + $(input[i]).val() + '",';
} else {
if ($(input[i]).attr('checked')) {
requestString += '"' + $(input[i]).attr('name') +'":"' + $(input[i]).val() +'",';
}
}
}
if (input.length > 0) {
requestString = requestString.substring(0, requestString.length - 1);
}
requestString += '}';
return requestString;
}
You can call the function like this:
buildRequestStringData($('#mainDiv'))
And the result http://jsfiddle.net/p7hbT/

Related

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

Check whether label is exist or not

I need to add checkbox dynamically by entering the label name.
Here I can add checkbox, but problem is if same label(case sensitive) is already present it should not allow user to add. Please help on this. Thanks in advance.
HTML
<input type="button" value="add" onClick="add()" />
<ul id="container" style="list-style-type:none;">
</ul>
Script
var i=0;
function add() {
var label = prompt("Please enter label name", "");
if (label != null || label != "") {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
Jsfiddle
Store the labels in an array and check whether the new label is present in that array or not, then proceed inserting the new element.
var i = 0;
var labels = [];
function add() {
var label = prompt("Please enter label name", "");
if (label != null || label != "") {
if (labels.indexOf(label) == -1) {
labels.push(label); i++;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">' + labels[labels.length - 1] + '</label>';
document.getElementById('container').appendChild(node);
} else {
alert("labels should be unique!")
}
}
}
DEMO
You can try something like this:
var i=0;
function add() {
var label = prompt("Please enter label name", "");
var exists = document.evaluate('//label[text()="' + label + '"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, exists).snapshotItem(0);
if (exists) {
return;
}
if (label != null || label != "") {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
You can use data attribute and querySelector to check for the existance.
var i=0;
function add() {
var label = prompt("Please enter label name", "");
var labels = ;
if ((label != null || label != "") && !document.querySelector('label[data-value="'+label+'"]')) {
i++;
var title = label;
var node = document.createElement('li');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '" data-value="'+title+'">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}

AngularJS ng-model binding with dynamic elements

I am dynamically creating elements based on json data that i get from a service. The elements are being created fine but the values are not being bound to the model via ng-model. I tried putting the function in $timeout to force $apply(). Even that did not work. Following is the code :
function InstructionsCtrl($http, ApiCallFactory, $timeout) {
var insCtrl = this;
insCtrl.data = [];
insCtrl.answers = {};
insCtrl.questionGroup = ApiCallFactory.questionGroup;
$timeout(function(){
var html = "";
var questionSet;
for (var tempQuestionSet in insCtrl.questionGroup) {
if (insCtrl.questionGroup.hasOwnProperty(tempQuestionSet)) {
questionSet = insCtrl.questionGroup[tempQuestionSet];
for (var question in questionSet) {
if (questionSet.hasOwnProperty(question)) {
if (questionSet[question].type == 'text') {
html += ' <div class="form-group"> <label for="text">' + questionSet[question].text + '</label> <input type="text" class="hi" id="text" ng-model="insCtrl.answers.';
html += tempQuestionSet + '.' + question + '" value ="text" name="radio1"> </div> '
}
else if (questionSet[question].type == 'select') {
var noOfOptions = questionSet[question].values.length;
html += ' <div class="form-group"> <label for="radio">' + questionSet[question].text;
html += '<select>';
for (var i = 0; i < noOfOptions; i++) {
html += '<option>' + questionSet[question].values[i] + '</option>';
}
html += '</select></div>'
}
}
}
}
}
var formContainer = $('#jsonTest');
formContainer.empty();
formContainer.prepend(html);
});
}
I've currently added ng-model only to the text type fields. Pls let me know what i am doing wrong.

Jquery not appending values correctly

I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code
<script>
function fillin(entire,name,id,key) {
if (entire.checked == true) {
var split_info = new Array();
split_info = name.split(":");
var div = $("#Inputfields"+id);
var till = (div.children("input").length)/4;
var current_count = 0;
for (var j=0;j<till;j++) {
if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") {
document.getElementById("insertname_"+j+"_"+id).value = split_info[0];
document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1];
break;
} else
current_count = current_count+1;
if (current_count == till) {
var x= addnew(id);
x =x+1;
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
document.getElementById("insertname_"+x+"_"+id).text = split_info[0];
//alert(document.getElementById("insertname_"+x+"_"+id).value);
//document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1];
}
}
} else {
}
}
</script>
<script>
function addnew(n) {
//var id = $(this).attr("id");
var div = $("#Inputfields"+n);
var howManyInputs = (div.children("input").length)/4;
alert(howManyInputs);
var val = $("div").data("addedCount");
var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">';
var fin = a+b+d+c;
$(fin).appendTo(div);
div.data("addedCount", div.data("addedCount") + 1);
return howManyInputs;
}
</script>
UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x
The problem is probably here:
document.getElementById("insertname_"+x+"_"+id).text
There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do:
document.getElementById("insertname_"+x+"_"+id).innerHTML = ...
or
$("#insertname_"+x+"_"+id).text(...);
Also, these lines:
$("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0];
alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value);
.value there should be replaced with .val(), because those are jQuery objects.
I have reworked a lot of your code for a lot of reasons. Compare the two.
function fillin(entire, name, id, key) {
if (entire.checked) {
var split_info = [];
split_info = name.split(":");
var div = $("#Inputfields" + id);
var till = (div.children("input").length) / 4;
var current_count = 0;
var j = 0;
for (j = 0; j < till; j++) {
var myj = j + "_" + id;
if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") {
$("#insertname_" + myj).val(split_info[0]);
$("#insertnumber_" + myj).val(split_info[1]);
break;
} else {
current_count = current_count + 1;
}
if (current_count === till) {
var x = addnew(id) + 1;
div.find("#insertname_" + x + "_" + id).val(split_info[0]);
alert(div.find("#insertname_" + x + "_" + id).val());
$("#insertname_" + x + "_" + id).val(split_info[0]);
}
}
}
}
function addnew(n) {
var div = $("#Inputfields" + n);
var howManyInputs = (div.children("input").length) / 4;
alert(howManyInputs);
var myi = (howManyInputs) + '_' + n + '"';
var val = div.data("addedCount");
var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">';
var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">';
var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">';
var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">';
var fin = a + b + d + c;
$(fin).appendTo(div);
div.data("addedCount", val + 1);
return howManyInputs;
}

Add submit button to jquery search form

I am trying to add a submit and a clear button to a quicksearch form in flexigrid. At the moment, when a user searches, they have press the enter key (13). So in conjunction with that, I would also like buttons that search and clear. I know I did this before, but cannot find the code after a restore. Many thanks
//add search button
if (p.searchitems) {
$('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>");
$('.pSearch', g.pDiv).click(function () {
$(g.sDiv).slideToggle('fast', function () {
$('.sDiv:visible input:first', g.gDiv).trigger('focus');
});
});
//add search box
g.sDiv.className = 'sDiv';
var sitems = p.searchitems;
var sopt = '', sel = '';
for (var s = 0; s < sitems.length; s++) {
if (p.qtype == '' && sitems[s].isdefault == true) {
p.qtype = sitems[s].name;
sel = 'selected="selected"';
} else {
sel = '';
}
sopt += "<option value='" + sitems[s].name + "' " + sel + " >" + sitems[s].display + " </option>";
}
if (p.qtype == '') {
p.qtype = sitems[0].name;
}
$(g.sDiv).append("<div class='sDiv2'>" + p.findtext +
" <input type='text' value='" + p.query +"' size='30' name='q' class='qsbox' /> "+
" <select name='qtype'>" + sopt + "</select></div>");
//Split into separate selectors because of bug in jQuery 1.3.2
$('input[name=q]', g.sDiv).keydown(function (e) {
if (e.keyCode == 13) {
g.doSearch();
}
});
$('select[name=qtype]', g.sDiv).keydown(function (e) {
if (e.keyCode == 13) {
g.doSearch();
}
});
$('input[value=Clear]', g.sDiv).click(function () {
$('input[name=q]', g.sDiv).val('');
p.query = '';
g.doSearch();
});
$(g.bDiv).after(g.sDiv);
}
ok you can try something simple like that :
$('.sDiv2').append("<input type='submit' value='submit' name='submit' /><input type='reset' value='reset' name='reset' />");
After you set listeners like you did for the others input

Categories