Object required error Java Script - javascript

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.

Related

How to handle Jquery custom funtions undefined scenario?

I defined a custom funtion in jquery like below
jQuery.predictiveTextInit = function (obj, options) {
//do something
}
and i am calling the funtion like below
<script>
$(document).ready(function () {
assignselectedvalues();
})
function getpredictions_c(e, selector, loc) {
localStorage['SearchCache'] = "";
$(".myInputContainer2").hide();
var hdnPredictiveval = $('#hdnPredictiveURL').val();
var formatselector = "." + selector;
var formatloc = "." + loc; //".searchCommunityLocation";//"." + loc;
var ptObj = { url: hdnPredictiveval, suggestContainer: formatselector };
$.predictiveTextInit($(formatloc), ptObj);
$(".searchCommunityLocation").val(e.target.value);
}
</script>
html
<input type="text" class="#searchCommunityLocation" onkeyup="getpredictions_c(event,'#dynamicContainer','#searchCommunityLocation')" name="searchCommunityLocation" id="searchCommunityLocation"/>
but some times i am getting error saying like $.predictiveTextInit is not a function but sometimes works fine what could be reason?
thanks in advance

Pass input text value to javascript not working

Good day. I have read and done almost all of the solution in the questions but cant seem to solve my problem. As written in my question, in mvc, i am passing a value from controller to view a string and then get by javascript to run a modal if ever a certain condition is met. please help. thanks.
here is the code in my controller:
public ActionResult Series()
{
List<sample> series = db.samples.Where(x => x.status == "False").ToList();
if ( series.Count == 0)
{
ViewBag.Info = "None";
}
else {
ViewBag.Series = series;
ViewBag.Info = "Have";
}
return View();
}
My View:
<input type="text" value="#ViewBag.Info" id="info" name="info" />
My Javascript:
#section Scripts{
<script>
$(window).on('load', function () {
var modelll = document.getElementById("#(ViewBag.Info)").value;
var s_end = document.getElementById("myNumber2").value;
var s_current = document.getElementById("myNumber3").value;
var s_status1 = document.getElementById("status").value;
var s_id1 = parseInt(document.getElementById("myNumber").value);
var s_end2 = parseInt(s_end, 10);
var s_current2 = parseInt(s_current, 10);
var x = parseInt(s_current, 10) + 1;
document.getElementById("item1").value = s_id1;
document.getElementById("item2").value = s_end;
document.getElementById("item3").value = x;
document.getElementById("status2").value = s_status1;
if (modelll === 'Have')
{
if ((s_current2 > s_end2) && (s_current2 != s_end2)) {
$('#myModal').modal({ backdrop: 'static', keyboard: false });
$('#myModal').modal('show');
}
}
else
{
$('#myModal').modal({ backdrop: 'static', keyboard:false });
$('#myModal').modal('show');
}
});
</script>
}
getElementById need an ID but you are passing #ViewBag.Info. change it to :
var modelll = document.getElementById("info").value;
also you are making many extra variables which are not really needed. for example to get what you have in s_current2, you can use
var s_current = parseInt(document.getElementById("myNumber3").value, 10);
no need to create another variable to convert it to integer.
To get the value from textbox
var modelll = document.getElementById("info");
To set the value to textbox
document.getElementById("info").value = var modelll;
you are using #ViewBag.Info instead of element id.
Following line is causing the problem in your code :
var modelll = document.getElementById("#(ViewBag.Info)").value;
// document.getElementById needs Id but you are passing #(ViewBag.Info) which is wrong
var modelll = document.getElementById("info").value; //info id of your textbox
// now check
if (modelll === 'Have')
{ }
else
{ }

Format number with commas in .each function

So I have some js which is converting a div class's number through a daily exchange rate engine. It outputs correctly as it should and I am now trying to separate this number it outputs using jQuery and a function I found whilst doing some research. I am trying to feed the number to the function using a .innerHTML method. I have got the function to alert a converted number but I have multiple elements which this function should run for, so have used an .each function - this is where something isn't working. I get no alert so I think there is something wrong with the .each code.
Can anyone see anything that might be causing it?
The complete code is here:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
//alert("Product Costs" + rate.toFixed(4))
}
$.getJSON("http://api.fixer.io/latest", demo);
});
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
</script>
I think the reason is
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
happends before you created the converted elements. Because you put the creation inside a get call.
I suggest you put this inside the callback of your get call.
Something like this
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
//alert("Product Costs" + rate.toFixed(4))
});
$(".converted").each(function() {
var convertedPrice = $(this).html();
console.log(ReplaceNumberWithCommas(convertedPrice));
});
}
$.getJSON("https://api.fixer.io/latest", demo);

Accessing <div> elements by name in jQuery

I have the following content in -
var jsonObj = [ {"name" : "Jason"},{"name":"Bourne"},{"name":"Peter"},{"name":"Marks"}];
<!---->
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
function getNames(jsonObj){
var response = JSON.stringify(jsonObj);
for ( var i = 0, len = jsonObj.length; i < len; i++) {
var nameVal = jsonObj[i].name;
response = response.replace(nameVal,replaceTxt(nameVal,i));
}
return response;
}
function replaceTxt(nameVal,cnt){
return "<u id='"+cnt+"' name='names' >"+nameVal+"</u> ";
}
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
and html as below -
<button id="getname">Get Name</button>
<div id="nameData"></div>
Double clicking on names value doesn't generating alerts.
are you sure it is..
<dev id="nameData"></dev>
OR
<div id="nameData"></div>
this works...but you have an extra }); in the question...(don't know if it is a typo)
fiddle here
Try this:
$(document).ready(function(){
$('u[name="names"]').live("dblclick", function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
Try moving this code:
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
inside
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
like:
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
});
You don't need the last "});" Or you didn't paste the whole code.
Look here: http://jsfiddle.net/4cajw/1/
As your code suggest that you are .dblclick()ing on dynamically generated element, that don't work, you have to select parent elem which exist in the document
$(document).on('dblclick','u[name="names"]', function(){
var currentId = $(this).attr('id');
alert(currentId);
});
try this out.
JSON.stringify - object -> JSON.
JSON.parse - JSON -> object

jQuery & Handling Element ID's

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

Categories

Resources