I need to find the element clicked which causes a text input to blur and store it as a variable. how can I determine the id of the element that was clicked to cause the input 'textBox' to lose focus? I don't know if I am approaching this the right way, but this code below is what I have so far. I tried document.activeElement, but it only worked on inputs and not elements such as li's and anchor tags Thanks
javascript:
var elClicked;
$('textBox').blur(function(){
elClicked = // what is the id of the element that caused blur?
alert(elClicked);
});
html:
<input type = "text" id = "textBox">
<!-- example elements -->
<input type = button id = "element1" />
text
<ul><li id = "element3">list</li></ul>
By accessing the id property of the target.
$('textBox').blur(function(){
var target = event.explicitOriginalTarget || document.activeElement;
elClicked = target ;
alert(elClicked);
});
alternatively you could try an approach along these lines
var elClicked;
$(document).mousedown(function(e) {
elClicked = $(e.target);
});
$('textBox').blur(function(){
alert(elClicked);
});
You can store the id of anchor tag in a hidden field ,When it is clicked.And takeing that value you can find which element is clicked
Related
I have a buttton inside a table.
<input type="button" onclick="I_Have('IS-12-78',this)" class="i_have_it" value="Yes, I have">
When I click the button I need to get the value of select box in the same row.
I haven't maintained separate class or id for this select box.
function I_Have(itm_id,obj)
{
xmlReq=new XMLHttpRequest();
xmlReq.open("POST","./requests/store.jsp",false);
xmlReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlReq.send("item="+itm_id+"&wt=1");
if(xmlReq.responseText.trim()!="")
{
alert(xmlReq.responseText)
obj.style.display="none"
return false
}
//obj.innerHTML("Used")
obj.setAttribute('onclick','I_Dont_Have("'+itm_id+'",this)')
obj.setAttribute('value','No, I dont have')
obj.setAttribute('class','i_dont_have_it')
}
Using "this"(passed into the function) property can I get the value of select box in javascript.
You can use Dom object's previousElementSibling property:
this.previousElementSibling.value
Have a look on this fiddle.
But this will only work if select is immediate sibling of your button element.
If that's not your case then first get the parent element then reach to your required element:
window.callback = function(obj){
var parent = obj.parentElement;
// Uncomment following to get value from nearest <TD> if your htmls is structured in table
//parent = parent.parentElement;
var select = parent.getElementsByTagName('select')[0];
alert(select.value);
}
Here is updated fiddle.
<input type="checkbox" onfocus="EnsureSelectionHandlerOnFocus(event,this,12)" onclick="ToggleAllItems(event,this,12)" title="Select or deselect all items" class="s4-selectAllCbx">
Whenever I refresh the page, these attributes have been changed with "12" in both EnsureSelectionHandlerOnFocus and ToggleAllItems. Therefore, I would like to get "12" of the onfocus and set "12" to the onlick attribute with Javascript?
If I understand you correct, you want to extract the number - the last param of the inline event listeners?
//get the event, example EnsureSelectionHandlerOnFocus(event,this,12)
var event = document.getElementById('cbSelectAll').getAttribute('onfocus');
//extract the params, example event,this,12
var params = event.match(/\(([^)]+)\)/)[1];
//get the last param, example 12
var number = params.split(',')[2];
//outputs 12
console.log(number);
To set the onclick event number param :
var click = 'ToggleAllItems(event, this, NUMBER)';
click = click.replace('NUMBER', number);
document.getElementById('cbSelectAll').setAttribute('onclick', click);
Example alternatives to document.getElementById
//selecting the checkbox by its class (if the class is unique)
var element = document.querySelector('.s4-selectAllCbx');
console.log(element);
//alternatively selecting the checkbox by an attribute
var element = document.querySelector('[title="Select or deselect all items"]');
console.log(element);
or add an unique name to the checkbox :
<input type="checkbox" name="myCheckBox" ...>
var element = document.querySelector('[name="myCheckBox"]');
console.log(element);
both will return the checkbox. If multiple elements has the same class or the same attribute, the first occurrence in the document will be returned. Giving the checkbox an unique class is prefered, imho, since you will have to update your code each time you change the attribute of the title.
I don't know how to add name from my input into label attr for and same input as ID. They are in same div. Do you guys know how to do it ? Thank you.
Jquery:
$('input[type="text"]').each(function () {
var name = $("input").attr("name");
})
HTML:
<div data-role="fieldcontain">
<label>Name:</label>
<input type="text" name="fname" value="" />
</div>
Just get the previous element of this input field and change its text with this.name:
$('input[type="text"]').each(function() {
$(this).prop('id', this.name) // set 'id' of input field
.prev('label') // get previous sibling element
.attr('for', this.name); // set 'for' attribute
});
Use $(this)
$('input[type="text"]').each(function () {
var name = $(this).attr('name');
$(this).prev('label').text(name);
})
Use .prop() instead of .attr() Since, attr() gives you
the value of element as it was defines in the html on page load. It is
always recommended to use prop() to get values of elements which is
modified via javascript/jquery , as it gives you the original value of
an element's current state dom element
$('input[type="text"]').each(function () {
var name = $("input").prop("name");
$(this).prev('label').text(name);
});
I have 5 input box in my page. I want to check if any field is blank, i will show the error message using a span tag appending to that input field.
Here is my code:
function validateForm() {
// Declare all the local variable
var inputElements, inputId, inputType, i, inputLength, inputNode;
// Get all the input tags
inputElements = document.getElementsByTagName("input");
for(i = 0, inputLength = inputElements.length; i < inputLength; i++) {
inputId = inputElements[i].id; // Get the input field ID
inputType = inputElements[i].type; // Get the input field type
// We will ONLY look for input[type=text]
if(inputType === "text") {
inputNode = document.getElementById(inputId);
if(inputNode.value === "") {
var spanTag = document.createElement("span");
spanTag.innerHTML = inputFieldBlankErrorMessage;
console.log(inputNode.appendChild(spanTag));
}
}
}
return false; // Do Nothing
}
This is what i am getting
It should append after the input tag. I am getting a weird tag which i don't need. Please help!!!
You can't .appendChild() anything to an input node, since an input can have no descendants.
Instead, you should insert the new node after it, or something similar.
inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);
DEMO: http://jsfiddle.net/hMBHT/
Simply put you are not supposed to append any elements to input elements.
What you probably want is something like this:
<div class="field">
<input type="text" name="bla"/>
<span class="error">This field can't be blank!</span>
</div>
So you need to insert the span before or after the input element.
Here is an answer that shows you how.
I believe that your issue is that you are trying to append the span as a child of the input, not a sibling (which, I believe, is what you really want).
I can't to be sure without seeing your actual HTML, because I don't know how your inputs are situated in the DOM, but if they have separate parent elements, then you would replace:
inputNode.appendChild(spanTag);
. . . with
inputNode.parentNode.appendChild(spanTag);
Edit: FYI, the code that squint gave below (inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);) would be how you could do it if all of the inputs are under the same parent element. It all depends on how the DOM structure is set up.
When I click on the p element with an onclick attribute calling the make_child function I would expect it to append a div element when ever it is clicked but it seams to be only appending a text node to the paragraph element what is the cause of this?
<script type="text/javascript">
function make_child(text, id, type) {
var text = document.createTextNode(text);
var target = document.getElementById(id);
var add = document.createElement(type);
var addtext = add.appendChild(text);
target.appendChild(addtext);
}
</script>
<p id="changeme" onclick="make_child('I have changed', 'changeme', 'div')">Click me to change</p>
change the last line to this
target.appendChild(add);
now you are appending to the correct element
Try doing target.appendChild(add) instead of target.appendChild(addtext)
Edit (more detail):
The syntax for appendChild (from MDN) is:
var child = element.appendChild(child);
Where child is the element being appended. In this case, addtext = add.appendChild(text) is set to text rather than add. Just doing target.appendChild(add) should solve this problem.
This also means the variable addtext is useless; you can remove it leaving only
add.appendChild(text)
for that line.