Important note so people don't get caught out (like I did): This may look like jQuery, but it is not.
Honestly, I should've known better. I use $ for stuff other than jQuery. Oh well. Lesson learned! ~Niet the Dark Absol
Code :
(HTML):
<html>
<head>
<script src="selector.js"></script>
</head>
<body>
<label id="id">A label</label>
<script>
$("label #id").clicked(function(){
alert("ASDASD");
});
</script>
</body>
</html>
(JS):
/*
NAME : SELECTOR.JS
*/
function $(attr){
// Removed space in front of the variable
while(attr.charAt(0) == " "){
attr = attr.substr(1);
if(attr == ""){
return 0;
}
}
// Completed the query
if(attr.length > 1){
return Array.prototype.slice.call(document.querySelectorAll(attr));
}else{
if(attr.length == 1){
return new Object(document.querySelector(attr));
}else{
return null;
}
}
}
Object.prototype.clicked = function(script){
if(typeof(this) == "object"){
if(this.constructor == Array){
for(var i = 0; i < this.length; i++){
this[i].onclick = script;
}
}else{
if(this.constructor == Object){
console.log("SINGLE OBJECT : " + this);
console.log("SINGLE OBJECT : ONCLICK : " + this);
this.onclick = script;
}else{
console.log("ERROR : this.constructor is not 'Object' or 'Array'.");
return null;
}
}
}else{
console.log("ERROR : typeof(this) is not 'Object'.");
return null;
}
return this;
};
When I clicked the label, I cannot get the alert box seen.
What should I do? The file name is selector.js, for the js file.
I need the function to be ran. Pls help!
I think this is the minimized code.
The space is wrong, instead of $("label #id") it needs to be $("label#id"). With the space between label and #id you're searching for an element inside a label with id="id", without the space you're searching for a label with id="id".
The function
.clicked()
you used, is not a valid jQuery function. The one you are looking for is:
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
See here:
http://api.jquery.com/click/
Related
I have a big problem with quotes in java script and html dom.
I want to use just double quotes("), not ' at all!
Here is my code:
<a onclick="aClicked("<span onclick="spanClicked("You clicked me")">I'm an Span</span>")">Add span</a>
<script type="text/javascript">
function aClicked(str) {
$(document).append(str);
}
function spanClicked(str) {
alert(str);
}
</script>
Can anyone help throw kind of these problems!?
Tanks.
here is my original code (it work correctly but I just want to simplfy it and underestand it):
"I call this function with ajax"
<?php
function getTags() {
$values = ['test1', 'test2'];
$valuesString = '';
$baseSpanString = '<span><span class="tag">?</span><a onclick="Tags.Update($(this).parent().parent(), $(this).parent(), "tag");">x</a></span>';
foreach ($values as $tmpValue) {
if(trim($tmpValue) == '') {
continue;
}
$valuesString .= str_replace('?', $tmpValue, $baseSpanString);
}
$xhtml = '
<div>
<input type="text" onkeydown="return Tags.Insert($(this).parent(), $(this), event, \''.str_replace('"', '\\\'', $baseSpanString).'\', \'tag\');"/>
<textarea style="display:none;">'.implode('-', $values).'</textarea>
'.$valuesString.'
</div>
';
return $xhtml;
}
?>
<script type="text/javascript">
Tags = {};
Tags.Update = function(div, span, tagClass) {
div = $(div);
if(!div.length) {
alert('Error');
return false;
}
$(span).remove();
var tagsSpan = $('.'+tagClass, div);
var tagsString = [];
if(tagsSpan.length) {
$.each(tagsSpan, function(index, val) {
tagsString.push($(val).text());
});
}
$('textarea', div).text(tagsString.join('-'));
};
Tags.Insert = function(div, input, event, baseSpanString, tagClass) {
if (event.keyCode == 13)
{
div = $(div);
input = $(input);
if(!div.length || !input.length) {
alert('Error');
return false;
}
var val = input.val();
if(val && val != '') {
input.val('');
var spanString = baseSpanString.replace('?', val);
div.append(spanString);
}
var tagsSpan = $('.'+tagClass, div);
var tagsString = [];
if(tagsSpan.length) {
$.each(tagsSpan, function(index, val) {
tagsString.push($(val).text());
});
}
$('textarea', div).text(tagsString.join('-'));
return false;
}
};
</script>
Two answers:
Your string question
The right way instead
Your string question
' is the feature specifically designed for this. But sometimes this stuff does legitimately come up...
The key is to be aware of what kind of text you're dealing with at each stage:
Within the " of the attribute (onclick="..."), you're writing HTML text, even though what you're writing in that HTML text is JavaScript. So you can use " for quotes if you insist on not using '.
If you need to use a string within your JavaScript code (such as the onclick in the string we're passing aClicked) and insist on not using ', put a \ before the ".
If you need to use a quote within an HTML string within an HTML string (such as the string being passed to spanClicked, which is an HTML string inside a JavaScript string inside an HTML string), then you need something that will end up being " after the entities in the first HTML string are processed. So that's "
So:
<a onclick="aClicked("<span onclick=\"spanClicked("You clicked me")\">I'm an Span</span>")">Add span</a>
Example:
function aClicked(str) {
$(document.body).append(str);
}
function spanClicked(str) {
alert(str);
}
<a onclick="aClicked("<span onclick=\"spanClicked("You clicked me")\">I'm an Span</span>")">Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The right way instead
But again, this is all just a way to make your code complicated unmaintainable; instead, just use jQuery, as you're already using jQuery:
Example:
$("a").on("click", function() {
var span = $("<span>I'm a span</span>");
span.on("click", function() {
spanClicked("You clicked me");
});
$(document.body).append(span);
});
function spanClicked(str) {
alert(str);
}
<a>Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As you are using jQuery use unobtrusive event handlers, for this .on() method can be used. When generating elements dynamically you need to use Event Delegation.
I would also recommend you to use semantically correct elements, thus used <button> element
$("#addSpan").on("click", function() {
$('#container').append("<span class=\"myspan\">I'm an Span</span><br/>");
})
$("#container").on("click", ".myspan", function() {
console.log("You clicked me");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="addSpan">Add span</button>
<div id="container">
</div>
Better make it as a function like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="adds();">Add span</a>
<script type="text/javascript">
function adds(){
aClicked("<span onclick='spanClicked(\"You clicked me\")'>I'm an Span</span>");
}
function aClicked(str) {
$(document.body).append(str);
}
function spanClicked(str) {
alert(str);
}
</script>
I want to prompt user to enter a tag and it will list it in the console.log and will ask again until they type "quit". if that happens then I will use the documentwrite to list in the innertext what the previous tags been searched for.
var selector = prompt("Please enter a selector: ");
var selectorr = document.getElementsByTagName(selector);
var breaker = "quit";
breaker = false;
var textlogger = "elements have been found that match the selector ";
var lengthfinder = selectorr.length;
while(true) {
console.log(lengthfinder + textlogger + selector);
if (selector == breaker) {
for (var i=0; i<divs.length; i++) {
document.write.innerText(textlogger);
}
}
}
If you wanna try jQuery and something fun, take this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Loop with jquery deferred</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var loop = function () {
return $.Deferred(function (deferred) {
var selector = prompt("Please enter a selector: ");
var quit = 'quit';
var selectors = [];
while (selector && selector != quit) {
selectors.push(selector);
var elements = $(selector);
console.log(elements.length + " elements have been found that match the selector " + selector);
selector = prompt("Please enter a selector: ");
}
if (selector)
{
deferred.resolve(selectors);
}
else
{
deferred.reject();
}
}).promise();
};
$(function () {
loop().done(function (selectors) {
$($.map(selectors, function (item, index) {
return '<div>' + item + '</div>';
}).join('')).appendTo($('body'));
});
});
</script>
</head>
<body>
<div>
<iframe src="http://stackoverflow.com/questions/40392515/will-this-loop-correctly-and-be-able-to-list-tag-names"/>
</div>
</body>
</html>
Here is the version with comments and suggestions on where to put your necessary code for it to work.
Code Preview
var breaker = "quit",
textlogger = "elements have been found that match the selector ",
textList = new Array();
while (true) {
var selector = prompt("Please enter a selector: ");
if (selector == breaker) {
/*
Write your necessary output here
*/
/*
After output you break out
*/
break;
} else {
/*
Write It inside list
*/
textList.push(selector);
}
/*
Write necessary output in console
*/
console.log(selector);
}
I want to prompt user to enter a tag and it will list it in the
console.log and will ask again until they type "quit"
while ("quit" !== prompt("Tag name selector, type `quit` to exit", "quit")) {
console.log("in loop");
}
console.log("exit loop");
I will use the documentwrite to list in the innertext what the
previous tags been searched for.
Either you use: document.write("some text") to append to existing dom or you can use selectorr[i].innerText="some text"
Here is my small example that might help you:
var selector;
while ("quit" !== (selector = prompt("Tag name selector. Use `quit` to cancel search", "quit"))) {
var elements = document.getElementsByTagName(selector);
var count = elements.length;
while (count--) {
elements[count].innerHTML += " [matched]";
}
}
<span>This is my <span> tag 1</span>
<p>This is my <p> tag 1</p>
<div>This is my <div> tag 2</div>
<p>This is my <p> tag 3</p>
<span>This is my <span> tag 2</span>
i have problem with below code which i use for Jira. When i run the code, i get
Object required error at line 4
Could you please Help! the values for approver and assigne are right so there is no problem with them
<script type="text/javascript" charset="utf-8" id="priorityCustomFieldScript">
//utils(common)
var by_id=function(n){
var i=document.getElementById(n);
return { //error line
value:i.value,
set_value:function(v){i.value=v;}
};
};
function setSummaryAndSubmit(e){
e.preventDefault();
e.stopPropagation();
//utils
var id_set=function(n){
var v={};
v.a=function(x,y){v[x]=y;return v;};
v.g=function(){return v[by_id(n).value] || '';};
return v;
};
//approver
var by_id_11690=id_set('customfield_11690').
a('22468','205 SSNL SAP');
//assignee
var by_id_11690_1=id_set('customfield_11690:1').
a('22469','jpechea').
a('22470','amikusi');
var setter=(function(){
var d=new Date();
by_id('customfield_10146').set_value(d.getFullYear());
by_id('summary').set_value('ADI - '
+by_id('customfield_10146').value+' - '
+document.getElementById("customfield_10171").options[document.getElementById("customfield_10171").selectedIndex].text+' - '
+by_id_11690.g()+' - '
+by_id('customfield_10163').value);
//by_id('assignee').set_value(by_id_11690_1.g());
by_id('assignee-container').set_value(by_id_11690_1.g());
var selectedGlobalId;
selectedGlobalId=document.getElementById('assignee-container').value;
jQuery("#assignee").find('option').remove();
jQuery("#assignee").append("<option value='" + selectedGlobalId +"'>JIRA User</option>");
jQuery("#assignee").val(selectedGlobalId).attr("selected", "selected");
}());
//ok
//var form=this;
//form.submit();
jQuery("#customfield_10146").parents('form').submit();
}
jQuery(document).ready(function($) {
function hideSummaryAndAddSeverityHook(){
var row = document.getElementById("assignee-container");
if (row) {
row.style.display = 'none';
}
$('#customfield_10146').closest('div.field-group').hide();
$('#summary').closest('div.field-group').hide();
jQuery("input#issue-create-submit").click( function(event) {
setSummaryAndSubmit(event);});
jQuery("input#issue-edit-submit").click( function(event) {
setSummaryAndSubmit(event);});
}
var currentLocation = window.location.href;
if (currentLocation.indexOf('CreateIssue') > -1 || currentLocation.indexOf('EditIssue') > -1)
{
hideSummaryAndAddSeverityHook();
JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function (e,context) {
hideSummaryAndAddSeverityHook();
});
}
});
</script>
document.getElementById() returns null if no element is found - you need to check for that in your code. The error you're getting means that i isn't an object - so document.getElementById() returned null in one of your calls.
Here is the code:
- here i've declared my variables:
var first = $('#first');
var firstError = $('#firsterror'); // the errors are in span tags (if it matters)
// and so on...
first.blur(validateFirst);
last.blur(validateLast);
username.blur(validateUsername);
password.blur(validatePassword);
confpassword.blur(validateConfpassword);
month.blur(validateMonth);
day.blur(validateDay);
year.blur(validateYear);
gender.blur(validateGender);
$('#myForm').submit(function(){
if( validateFirst() & validateLast() & validateUsername() & validatePassword() & validateConfpassword() & validateMonth() & validateDay() & validateYear() & validateGender() ){
return true;
}else{
return false;
}
});
function validateFirst(){
if(first.val().length < 5){
first.addClass('error_input');
firstError.text('You left this empty!');
firstError.addClass('error');
return false;
}else{
first.removeClass('error_input');
firstError.text('');
return true;
}
};
// and so on... I would like the code to work as so: When an input recives focus the error should hide else the code should run exactly as it is.
thank you..
I think you should use jQuery validate lib to validate your form here is cdn link of jQuery validate..
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
Note that you have to include jQuery lib before that line
All you have to do is just write few lines of code as below
$('#form_id').validate({
rules : {
'el_name' : 'validation_rule' // like, required
},
messages : {
'el_name' : 'Your error message'
}
});
Try this
$('.error_input').focus(function(){
$(this).removeClass('.error_input');
});
did you try something like this already?
function removeError() {
$(this).removeClass('error_input');
$("#error"+$(this).attr("id")).text("").removeClass("error");
}
first.focus(removeError);
last.blur(removeError);
username.blur(removeError);
....
I have the following code:
function mandatoryField(manF)
{
var fieldId = $(manF).val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
It doesn't work, but this does:
function mandatoryField()
{
var fieldId = $("#element_1").val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
Presume, on my first example, mandatoryField is called as such:
mandatoryField("#element_1")
Why doesn't it work when I try to replace the absolute element ID name with a variable?
Edit:
Most recent code - non-working:
function isAmExSelected()
{
return $("#creditCardType").val() == "American Express";
}
function containsOnlyDigits(str)
{
return str.match(/[^0-9]/) == null;
}
function validateCCNumber()
{
var ccn = $("#creditCardNumber").val();
var onlyDigits = containsOnlyDigits(ccn);
if(isAmExSelected())
{
return ccn.length == 15 && onlyDigits;
}
else
{
return ccn.length == 16 && onlyDigits;
}
}
function mandatoryField(manF)
{
var fieldId = $("#" + manF).val();
return fieldId != "";
}
function registerValidation(id, validateMethod(), errorMethod)
{
$(id).change(function(){
if(validateMethod() == false)
{
errorMethod();
}
});
}
$(document).ready(function(){
registerValidation("#creditCardNumber", validateCCNumber, function(){alert("Invalid Credit Card Number!")});
$('input[type=text][class=mandatory]').blur(function(){
if (mandatoryField(this.id)) {
alert('Field:' + this.id + ' is mandatory!')
}
});
});
Edit 2
I've rewritten the entire thing to look like this:
$('input[type=text][class=mandatory]').blur(function(){
if (!($("#" + this.id).val().length)) {
alert('Field:' + this.id + ' is mandatory!');
}
});
If a text input of the mandatory class blurs, then run the function: if #foo.val() does not have length (i.e. has no text in it), run the alert. I believe it should work, but it does not.
Update your code to so:
function mandatoryField(manF)
{
var fieldId = $("#" + manF).val();
if(fieldId == "")
{
return false;
}
else
{
return true;
}
}
and then try again.
Both pieces of code should work the same irrespective of whether the selector is passed in as an argument, or provided as a literal to $ directly. Also, instead of the if..else, you could do
function mandatoryField(manF) {
var fieldId = $(manF).val();
return fieldId != "";
}
Try this one:
function mandatoryField(manF)
{
if($('#' + manF).val() == "")
{
return false;
}
else
{
return true;
}
}
mandatoryField("element_1");
But this will get you value of element, not it's id. I'm not sure what you are tring to accomplish.
Trigger on field blur option:
$('input[type=text][class=classForMandatoryFields]').blur(function(){
if (mandatoryField(this.id)) {
alert('Field:' + this.id + ' is mandatory!')
}
});
Could you try:
var fieldId = manF.val();
mandatoryField($("element_1"));
Besides your selector problem, you could rewrite your function like this:
function mandatoryField(manF){
return $(manF).val().length;
}
This is, because in JavaScript everything has a truth or false meaning. For numbers, 0 is false.
EDIT:
My test works just fine:
function mandatoryField(manF){
return $(manF).val().length;
}
(...)
<input id="test" value=""/>
<input type="button" value="dd" onClick="alert('length: ' + (mandatoryField('#test'))"/>
Okay this will not work because jquery will assume manF is a DOM object but instead you are passing string.
have you ever tried
var tr = $('#element1') //----------1
alert($(tr).val()) //------------2
tr is actually a dom object
UPDATE::
why don't you try this one
//some code on some event
if(!check_mandatory())
//do something else
else do another thing
//some code on some event
and the function
function check_mandatory()
{
$('.mandatory').each(function{
if($(this).val() == ""){
alert($(this).attr("name") + "required");
//or you can use id or any attrib
return false;
}
})
}
note code might not work not tested, if it did not work then let me know