JQuery: Selecting elements with unique class AND id - javascript

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery

so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example

I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.

$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

Related

Show/Hide Form elements based on json response

I make an api call and get a json Response that looks like this:
{"Field":"Amount","FieldName":"Amount","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"Mandatory"}
The api call Returns between 5-10 of These objects.
In my html i have the fields inside a form, and they look as follow
<div class="form-group">
<label class="col-md-4 control-label" for="Amount">Amount</label>
<div class="col-md-4">
<input name="amount" class="form-control input-md" id="amount" type="text" placeholder="placeholder">
</div>
</div>
Now, depending on the json repsonse, i Need to show/hide different fields. Additionally, i Need to pass the min and max length, aswell as whether it's required or not ("Options":"Mandatory", in this example) Attributes to html, so the front end is already validate (obviously, further validation will be done server-side).
What's the best way to do this?
Edit:
I hide the Form Elements by using class="hidden". Also, every form element has a class that is identical to the id of the form element.
What i've tried so far is the following:
var ids = [];
for(var item in data) {
ids.push(data[item]['Field']);
$("." + ids[ids.length]).removeClass("hidden");
}
So in the above example, what i was hoping would happen in the first Iteration is that
$("." + ids[ids.length]).removeClass("hidden");
changes to
$(.Amount).removeClass("hidden");
and therefor show the form element.
Thanks
The problem is in this line
$("." + ids[ids.length]).removeClass("hidden");
When you push one element to ids array the length becomes 1 and your element is in 0th position but you are accessing element in first position.
To correct it change the line to
$("." + ids[ids.length - 1]).removeClass("hidden");
I ended up solving it like this:
var ids = [];
var minlength = [];
var maxlength = [];
var required = [];
for(var item in data) {
//push values into array
ids.push(data[item]['Field']);
maxlength.push(data[ids.length-1]['MaximumLength']);
minlength.push(data[ids.length-1]['MinimumLength']);
required.push(data[ids.length-1]['Options']);
//removes the class hidden and therefor shows the Element
$("." + ids[ids.length-1]).removeClass("hidden");
//adds the Attribute minlength to the html element
$("#" + ids[ids.length-1]).attr('minlength', minlength[minlength.length-1]);
//adds the Attribute maxlengthto the html element
$("#" + ids[ids.length-1]).attr('maxlength', maxlength[maxlength.length-1]);
//if the value in the Array is "Mandatory", adds the Attribute "required" to the html element
if (required[ids.length-1] == "Mandatory") {
$("#" + ids[ids.length-1]).attr('required', "required");
}

How to select text value from a variable div id tag?

<div id="Modal<%= index %>">
<div>
<input type="text" id="textvalue">
</div>
</div>
In the above code I need to get value of text field but the problem coming is the div id is variable according to index i.e it may be 'Modal0' or 'Modal1' or 'Modal"n"' depending on value of index. So, if i write $(#textvalue).val() then it is always giving the text entered in id 'Modal0'. What will be solution for this? And the big issue is that I can not use 'Modal0' or 'Modal1' ... id because that is generated dynamically.
you can use closest jquery function like that make dive id is different.
closest will fetch the parent tag.
$(diveid).closest("diveid").inoutid.val();
You should include the parent div in the query as well, for example:
$("#Modal0 input").val();
First you should select the div you´re looking for , then find it's text-input
$('#Modal0').find('#textvalue').val();
$('#Modal1').find('#textvalue').val();
Im not sure if this is what you're trying to do, but if the clicking of buttons will only affect the ID of the same container div of the input.textvalue element then this will do the trick:
$('div[id^=Modal] #textvalue').val());
DEMO:
$(function(){
$('a').on('click', function(e) {
const ID = $(this).attr('href')
const counterID = ID.substring(ID.length-1);
const targetID = $('div[id^="Modal"]').attr('id');
$('div[id^="Modal"]').attr('id', 'Modal'+(counterID-1));
console.log('DIV ID:', 'Modal'+(counterID-1));
});
$('button').on('click', function(){
console.log('DIV ID: ' + $('div[id^=Modal]').attr('id'), ' ,TEXT VAL: ' + $('div[id^=Modal] #textvalue').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Modal 1
Modal 2
Modal 3
<div id="Modal">
<div>
<input type="text" id="textvalue">
</div>
<button>submit</button>
</div>

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

Place div.innerHTML as a hidden form value

I have a long page with identical section I am attempting to combine into one that has:
TITLE
description
form
I have working mouseovers that change the title and description, but need a solution to change the value of a hidden form input to the new titles when changed.
HOW do I get the hidden form value to change onmouseover to equal current TITLE.value?
Milestones
PHP
function changeContent(id, msg) {
var el = document.getElementById(id);
if (id) {
el.innerHTML = msg;
}
}
FORM
<input type="hidden" value="" name="category" />
Is this what you're looking for?
document.getElementById('hiddenInputId').value = msg;
Your hidden element doesn't have an Id, so you can use following:
var elems = document.getElementsByName('category');
elems[0].value = <<new value>>
getElementsByName always returns an array so you have to pickup first element and set its value.
Cheers !!

How can I create dynamic controls and put their data into an object?

I created a div and a button. when the button clicked, there will be a group of element(included 1 select box and 2 text inputs) inserted into the div. User can add as many group as they can, when they finished type in data of all the group they added, he can hit save button, which will take the value from each group one by one into the JSON object array. But I am stuck in the part how to get the value from each group, so please help, thank you.
The code for the div and the add group button function -- AddExtra() are listed below:
<div id="roomextra">
</div>
function AddExtra() {
$('#roomextra').append('<div class=extra>' +
'<select id="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" id="insetLength">' +
'Width(m): <input type="text" id="insetWidth">' +
'Height(m): <input type="text" id="insetHeight">' +
'</div>');
}
function GetInsetOffSetArray (callBack) {
var roomIFSDetail = [{
"IsInset": '' ,
"Length": '' ,
"Width": '' ,
"Height": ''
}];
//should get all the value from each group element and write into the array.
callBack(roomIFSDetail);
}
This should just about do it. However, if you're dynamically creating these groups, you'll need to use something other than id. You may want to add a class to them or a data-* attribute. I used a class, in this case. Add those classes to your controls so we know which is which.
var roomIFSDetail = [];
var obj;
// grab all of the divs (groups) and look for my controls in them
$(.extra).each(function(){
// create object out of select and inputs values
// the 'this' in the selector is the context. It basically says to use the object
// from the .each loop to search in.
obj = {
IsInset: $('.isInset', this).find(':selected').val() ,
Length: $('.insetLength', this).val() ,
Width: $('.insetWidth', this).val() ,
Height: $('.insetHeight', this).val()
};
// add object to array of objects
roomIFSDetail.push(obj);
});
you'd better not to use id attribute to identity the select and input, name attribute instead. for example
$('#roomextra').append('<div class=extra>' +
'<select name="isInset">' +
'<option value="Inset">Inset</option>' +
'<option value="Offset">OffSet</option>' +
'</select>' +
'Length(m): <input type="text" name="insetLength">' +
'Width(m): <input type="text" name="insetWidth">' +
'Height(m): <input type="text" name="insetHeight">' +
'</div>');
}
and then, usr foreach to iterate
$(".extra").each(function() {
var $this = $(this);
var isInset = $this.find("select[name='isInset']").val();
var insetLength = $this.find("input[name='insetLength']").val();
// ... and go on
});
A common problem. A couple things:
You can't use IDs in the section you're going to be repeating, because IDs in the DOM are supposed to be unique.
I prefer to use markup where I'm writing a lot of it, and modify it in code rather than generate it there.
http://jsfiddle.net/b9chris/PZ8sf/
HTML:
<div id=form>
... non-repeating elements go here...
<div id=roomextra>
<div class=extra>
<select name=isInset>
<option>Inset</option>
<option>OffSet</option>
</select>
Length(m): <input id=insetLength>
Width(m): <input id=insetWidth>
Height(m): <input id=insetHeight>
</div>
</div>
</div>
JS:
(function() {
// Get the template
var container = $('#roomextra');
var T = $('div.extra', container);
$('#addGroup').click(function() {
container.append(T.clone());
});
$('#submit').click(function() {
var d = {};
// Fill d with data from the rest of the form
d.groups = $.map($('div.extra', container), function(tag) {
var g = {};
$.each(['isInset', 'insetLength', 'insetWidth', 'insetHeight'], function(i, name) {
g[name] = $('[name=' + name + ']', tag).val();
});
return g;
});
// Inspect the data to ensure it's what you wanted
debugger;
});
})();
So the template that keeps repeating is written in plain old HTML rather than a bunch of JS strings appended to each other. Using name attributes instead of ids keeps with the way these elements typically work without violating any DOM constraints.
You might notice I didn't quote my attributes, took the value attributes out of the options, and took the type attributes out of the inputs, to keep the code a bit DRYer. HTML5 specs don't require quoting your attributes, the option tag's value is whatever the text is if you don't specify a value attribute explicitly, and input tags default to type=text if none is specified, all of which adds up to a quicker read and slimmer HTML.
Use $(".extra").each(function() {
//Pull info out of ctrls here
});
That will iterate through all of your extra divs and allow you to add all values to an array.

Categories

Resources