How can I select an element on the form and perform click action on it using jQuery? Here's an example for what I want:
If I have many image buttons created on the runtime and here's one of them:
<img class="arrow arrowDown" onclick="toggleMyChildren(this);" alt="" src="/sp.gif" complete="complete" svalue="2"/>
How can I select this element and perform "Click" action on it depending on the value of attribute's (svalue) value?
$(document).ready(function() {
$("img[svalue=2]").on("click", function() {
var attr = $(this).attr("svalue")
alert(attr);
});
});
or if you need attribute on click :
function toggleMyChildren(ooo) {
var attr = $(ooo).attr("svalue")
alert(attr);
}
Related
I am creating a form builder script. I have a select input where the user can select the form element they want to use, depending on their selection ("select", "checkbox" or "radio") another form field is displayed allowing users to input their options.
Users can create as many instances of form elements as they want, so each select input has a dynamically created id that corresponds to the id of the hidden form field. I then use jQuery to determine whether the "options" field should be hidden or not (triggered on change of the form elements select input).
Currently, for every instance, I have the following code addedabove the select input:
<script>
jQuery(document).ready(function($) {
var arr = ['select', 'checkbox', 'radio'];
var thisForm = 'select.input-type-118';
function showHideSelect() {
var val = $(thisForm + ' option:selected').val();
var selectOptions = $('#select-options-118')
if (arr.indexOf(val) >= 0) {
selectOptions.show();
} else {
selectOptions.hide();
}
}
showHideSelect();
$(thisForm).change(function() {
showHideSelect();
});
});
</script>
Where var thisForm and var selectOptions are added dynamically and refer to the select option below this script.
I'm wondering if there is a better way to do this rather than repeat several instances of this, at the moment, a users page cold look like this:
<script>
...
</script>
<select>
...
</select>
<textarea>
This is hidden depending on the select option
</textarea>
<script>
...
</script>
<select>
...
</select>
<textarea>
This is hidden depending on the select option
</textarea>
<script>
...
</script>
<select>
...
</select>
<textarea>
This is hidden depending on the select option
</textarea>
...etc...etc
My concern is that I don't think it's best practice to have so many instances of the same script, but I'm unsure how to write a global script that will allow me to show/hide the textarea on an individual basis.
I have shown a more accurate depiction of my workings on this jsfiddle here:
https://jsfiddle.net/46stb05y/4/
You can use Event Delegation Concepts. https://learn.jquery.com/events/event-delegation/
With this you can change your code to
$(document).on('change','select',function() { //common to all your select items
showHideSelect($(this)); // passing the select element which trigerred the change event
});
This will work even on the select items that are added dynamically
You must change your function to receive the element as the parameter.
function showHideSelect($selectElement) {
var val = $selectElement.val();
var selectOptionsId = $selectElement.attr('class').replace('input-type','select-options');
var selectOptions = $("#"+selectOptionsId);
if (arr.indexOf(val) >= 0) {
selectOptions.show();
} else {
selectOptions.hide();
}
}
Here is the Working JsFiddle
I want to implement a functionality in which, whenever a user checks a checkbox, it will get replace with a check image. For example:
So if I select first option it should get replace with a check image.
I am able to replace the checkbox with image, but this new element looses the ng-click event.
Below is the code:
currentController.changeChoice = function ($event, value) {
if ($event.target.checked) {
currentController.selectedOptions.push(value);
$($event.target).replaceWith('<div ng-click="stock.changeChoice($event,option);"><img src="../images/check.png" alt="remove" ng-checked="stock.selectedOptions.indexOf(option) > -1" /> </div>');
}
else {
var index = currentController.selectedOptions.indexOf(value)
currentController.selectedOptions.splice(index, 1);
}
};
below is the html generated for the new element (image)
<div ng-click="stock.changeChoice($event,option);"><img src="../images/check.png" alt="remove" ng-checked="stock.selectedOptions.indexOf(option) > -1"></div>
If angular way you have to use ng-show(or ng-if) for hide or show image and checkbox depends of the state. They both have to use same on-click callback. Here is the basic idea on pseudocode
<input ng-show="!is_checked" ng-click="callback()" ... />
<img ng-show="is_checked" ng-click="callback()" ... />
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.
Expanding on the question here: How to use javascript to swap images with option change?
In accordance with the method in that question of changing an image based on a select option, how would I also change the <a></a> link around the image to mirror the displayed image?
<script>
var colorUrlMap = {
"Black/White" : "images/taylormade_purelite_standbag_bk.jpg",
//Add more here
"White/Red/Black" : "images/taylormade_purelite_standbag_wrb.jpg"
};
</script>
<select name="Color:"onchange="document.getElementById('myimage').src = colorUrlMap[this.value];">
<option value="Black/White">Black/White</option>
<!-- Add more here -->
<option value="White/Red/Black">White/Red/Black</option>
</select>
<img src="images/taylormade_purelite_standbag_bk.jpg" id="myimage">
example:
<a href="WHATEVER IS CHOOSEN BASED ON THE urlMAP"><img src="images/taylormade_purelite_standbag_bk.jpg" id="myimage">
</a>
Since you are doing multiple things now, it would be better to break that change code into its own function. But basically you need to access the href attribute of the a tag the same way you are accessing the src on the img tag.
<script>
var colorUrlMap = {
"Black/White" : "images/taylormade_purelite_standbag_bk.jpg",
//Add more here
"White/Red/Black" : "images/taylormade_purelite_standbag_wrb.jpg"
};
function changeSelect(el) {
document.getElementById('myimage').src = colorUrlMap[el.value];
document.getElementById('link_id').href = colorUrlMap[el.value];
}
</script>
<select name="Color:" onchange="changeSelect(this)">
<option value="Black/White">Black/White</option>
<!-- Add more here -->
<option value="White/Red/Black">White/Red/Black</option>
</select>
<img src="images/taylormade_purelite_standbag_bk.jpg" id="myimage">
example:
<a id="link_id" href="WHATEVER IS CHOOSEN BASED ON THE urlMAP"><img src="images/taylormade_purelite_standbag_bk.jpg" id="myimage">
</a>
You may notice that I also gave the a an id value.
update
If you need to get that link from somewhere else, here is a possible alternative way to write your script. I added another level of properties to each color item: a src and href to match the attribute names you are updating on the a and img tags.
<script>
var colorUrlMap = {
"Black/White" : {
"src" : "images/taylormade_purelite_standbag_bk.jpg",
"href" : "your link here"
},
//Add more here
"White/Red/Black" : {
"src" : "images/taylormade_purelite_standbag_wrb.jpg",
"href" : "your other link here"
}
};
function changeSelect(el) {
document.getElementById('myimage').src = colorUrlMap[el.value].src;
document.getElementById('link_id').href = colorUrlMap[el.value].href;
}
</script>
update 2
To address the question in the comments about radio buttons, yes. From your code example, currently you have a form submission on the onclick event of the radio. You would need to change that. The trick with radio buttons however, is that you only want to use the value of the selected radio. If you use the onchange event on the radio, it will fire both when it is selected and deselected.
So if you want to use the same function for both radios and selects, you can wrap the setter lines in an if statement:
function changeColor(el) {
if (el.nodeName != "INPUT" || el.checked) {
document.getElementById('myimage').src = colorUrlMap[el.value].src;
document.getElementById('link_id').href = colorUrlMap[el.value].href;
}
}
This should work on select, input[type=radio], and input[type=checkbox]. You can put it in a onclick, onchange, or onkeyup handler. (onkeyup is good when the keyboard is used to change the values.)
<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.