Weird javascript problem - javascript

i'm building a page that is dinamically loaded with ajax.
This is what the '$.get' jQuery function calls (this is located on an external HTML page):
<script type="text/javascript">
$(function()
{
$('button').sb_animateButton();
$('input').sb_animateInput();
$('#settings_security_error').hide();
});
function check_passwords(password, password_confirm)
{
$('#settings_security_error').show();
alert('I\'m in funcion!'); // This works...
if(password.length < 4) // ... this doesn't
{
$('#settings_security_error').innerHTML = 'Password too short';
}
else
{
password = hex_md5(password);
password_confirm = hex_md5(password_confirm);
$.get('/engine/ajax/check_password.php?password=' + password + '$password_confirm=' + password_confirm,
{language: "php", version: 5},
function(result)
{
$('#settings_security_error').innerHTML = result;
},
'html');
}
}
</script>
<div class="title">Security</div>
<table class="sub_container">
<tr>
<td><label>Old password</label></td>
<td class="td_input"><input type="password" name="old_password"/></td>
</tr>
<tr>
<td><label>New password</label></td>
<td class="td_input"><input type="password"
name="new_password"
id="settings_security_new_password"
onkeyup="check_passwords(this.value, getElementById('settings_security_password_confirm').value)"/></td>
</tr>
<tr>
<td><label>Confirm password</label></td>
<td class="td_input"><input type="password"
name="new_password_confirm"
id="settings_security_password_confirm"
onkeyup="check_passwords(getElementById('settings_security_new_password').value, this.value)"/></td>
</tr>
<tr>
<td class="td_error" id="settings_security_error"></td>
</tr>
</table>
And this is where the external HTML is placed...:
<div id="settings_appearance">
</div>
... from this javascript snippet:
function get_page_content(page, target_id)
{
$.get('engine/ajax/get_page_content.php?page=' + page,
null,
function(result)
{
$("#"+target_id).html(result); // Or whatever you need to insert the result
},
'html');
}
Well... the problem is that the javascript in the first snippet is executed when it's loaded by the $.get function, but i still can't understand the reason why when i type into the input boxes nothing happen. It should write the output of the javascript function check_passwords(password, password_confirm) in <td class="td_error" id="settings_security_error"></td>.
Thanks for helping.
Silvio

One problem will be this:
$('#settings_security_error').innerHTML = 'Password too short';
$('#settings_security_error') is a jQuery object; not a DOM element. You're meaninglessly setting the innerHTML property on a jQuery object; which won't do anything useful.
If you want to set the DOM elements innerHTML directly, do either:
$('#settings_security_error')[0].innerHTML = 'Password too short';
Or
$('#settings_security_error').get(0).innerHTML = 'Password too short';
Or you can use the jQuery .html() or .text() functions (text() being the quickest):
$('#settings_security_error').text('Password too short');
Or
$('#settings_security_error').html('Password too short');

Related

My angular can't get the value from html page

I have an angular function to call me rest service but it can't get the value from the html file. when i press submit the $scope.productForm is, although i still have value in my html page.
Main.js
$scope.products = [];
$scope.productForm = {
ID:1,
Name:"",
Description:"",
URL:""
};
_refreshProductData();
//Add or Update Product
$scope.submitProduct = function() {  
var method = "";
 
if ($scope.productForm.ID == -1) {
    method = "POST";
} else {
    method = "PUT";
}
 
$http({
    method: method,
    url: '/product',
    data: angular.toJson($scope.productForm),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(_success, _error);
}
index.html
<form ng-submit="submitProduct()">
    <table border="0">
        <tr>
            <td>ProductID</td>
            <td>{{productForm.ID}}</td>
        </tr>
        <tr>
            <td>Product Name</td>
            <td><input type="text" ng-model="productForm.Name" /></td>
        </tr>
        <tr>
            <td>Product Description</td>
            <td><input type="text" ng-model="productForm.Description"  /></td>
        </tr>
<tr>
            <td>Product URL</td>
            <td><input type="text" ng-model="productForm.URL"  /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Submit" class="blue-button" />
            </td>
        </tr>
   </table>
</form>
data: angular.toJson($scope.productForm) can have value from index.html
Like others have said, you have a number of things you need to address.
main.js doesn't have a function _refreshProductData defined. I'm assuming this is breaking your script and why $scope.submitProduct() isn't executing.
When defining your _refreshProductData function, you need to attach it to the controller's $scope(i.e. $scope._refreshProductData = function(){//refresh data} if you want it to be accessible to the html template. Otherwise, you wouldn't need to attach $scope to it. You would need to update your call to this function based on the approach you take.
$scope._refreshProductData();--> you should call your function this way.
_refreshProductData();-->_refreshProductData is not defined(F12)
I have assumed that the function was created in my previous answer.
1)create your function in main.js
$scope._refreshProductData() = function()
{
write codes here...
}
then call the function in place
2) $scope._refreshProductData();

jquery within a javascript function not working

I am calling a javascript function from within my razor code..but the jquery code within my javascript function doesnot get executed..
what is the correct way of doing it.
function getPosition(id) {
var c = '#' + id;
return $c.index();
}
My HTML Table
<tbody>
<tr>
<td>
#foreach(Result geResults in Model.results)
{
#:
<script>
{
getPosition(#geResult.assessmentId);
}
</script>
}
</td>
</tr>
<\tbody>
UPDATE
As everybody is getting confused i am posting more detail
<table>
<thead>
<tr>
#foreach (Assessment geAssessment in Model.assessments)
{
<th id=#geAssessment.AssessmentID>#geAssessment.Name</th>
}
</thead>
<tbody>
<tr>
#{
// add a td for each assessment in body
foreach(Assessment geAssessment in Model.assessments)
{
<td>
#foreach (ShortResult geResult in Model.results)
{
#:
<script>
{ getPosition(#geResult.assessmentId);
}
</script>
}
</td>
}
}
</tr>
</tbody>
i want to return the column index in getPosition function and then print it in the td..hope this clears out any confusions
currently it says getPosition is out of context whereas intellisense shows me getPosition when i code
Just put c in brackets. It will be like this:
function getPosition(id) {
var c = '#' + id;
return $(c).index();
}
If it doesnt throw
$ Undefind error
first of all check that your passing the values means getPosition("") is not null secondly write in JavaScript
function getPosition($id) {
var c = '#' + $id +;
return $(c).index();
}

jQuery Click Event for Dynamically Created Links Not Working

I am displaying a list of users in a table. Then, I have a button to allow a user to view more details about a specific user. However, I am having a hard time getting the ID for the user that is clicked on. I am not sure why it's not working. What am I doing wrong? I tried several options, and none of them work.
Partial code of how data the links are generated in my view.
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
My jQuery function
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).attr('id');
console.log('dt');
});
});
I also tried it this way:
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
Here is the Javascript function that I created. It kept giving
function test(e){
console.log(e);
};
I get this error:
0x800a1391 - JavaScript runtime error: 'test' is undefined
updated on 11/21/15 #7:53 AM EST
I removed the for loop and created a single cell with 1 click button. The click event is not registered. I tried it with 'on', 'live', and 'delegate' with no success.
<div class="table table-responsive" style="width:100%;height:100%;">
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th><div class="centerText">Date Created</div></th>
<th colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="6"><div class="centerText">Detail</div></td>
</tr>
</tbody>
</table>
</div>
#section Scripts {
<script type="text/javascript">
$('.table tbody tr td div').delegate('.Detail','click', function ()
{
console.log('you click me');
});
</script>
}
You are trying to get the attribute id which doesn't exist. Use below to get data-id
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).data('id');
console.log(dt);
});
you can also use
var dt = $(this).attr("data-id");
Second one (remove var):
function test(e){
console.log(e);
};
Partial code of how data the links are generated in my view. change id instead of data-id.
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
My jQuery function
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).attr('id');
console.log('dt');
});
});
I also tried it this way:
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
Here is the Javascript function that I created. It kept giving. (Remove var before function).
function test(e){
console.log(e);
};
Here is how I reproduced your problem with JavaScript runtime error: 'test' is undefined.
Scenario
I guess that you've defined the function test probably in your jQuery DOM ready function $(function(){...}.
If so, the function test is undefined because by the time the DOM is loading, AND the event handlers on DOM elements are being registered (in your case the onclick in the link), the function test is not yet known to the document, and therefore undefined.
Solution
Try to move your test function's declaration outside of jQuery's DOM ready function. That is,
$(function(){
//code that has to run once the DOM is ready
});
function test(e){
console.log(e);
}
DEMO
I found what was causing the problem. I had a modal popup within the form. I was looking to add a textarea, so I added this code '
<textarea name="reasonForArchiveText" id="reasonForArchiveText" />
That's the code that was preventing me from getting the click event. As I was playing around with the code, I commented out the modal popup, and things started to work. Then, I commented section of the modal until I finally found the culprit. The minute that I commented it out, the code works.

jQuery parent() function returns empty

I have the following html (simplified to basic setup):
<div class="findme">
<table>
<tr>
<td>
<img id="image" src="image.png" onclick="findTheDiv(event)" />
</td>
</tr>
</table>
</div>
When I click on the image, the findTheDiv(event) function runs, which looks like this:
function findTheDiv(event) {
var elem = $(event.toElement);
var found = false;
// stop the loop if the top-level element is reached (html)
while (!$(elem).is("html")) {
if ($(elem).is("div.findme")) {
found = true;
break;
}
elem = $(elem).parent();
console.log(elem);
}
}
This runs, and for each iteration of the while loop, I log the new elem, which is the previous element's parent, to the console. This is the result I get:
[<img id="image" src="image.png" onclick="findTheDiv(event)">]
[<td>]
[<tr>]
[<table>]
[]
When the table is reached, it apparently has no parent, even though it clearly does, which is the div. To further test this, I used the console to execute this:
$("table").parent();
And it returned a blank array
[]
Why is jQuery saying the table does not have a parent, since all elements except for the <html> have parents?
I changed your code a little and it works fine. Instead of using an event object as an argument, I just pass this to reference the object which fires the event directly. This serves the same purpose.
function findTheDiv(elem) {
//var elem = $(event.toElement);
var found = false;
// stop the loop if the top-level element is reached (html)
while (!$(elem).is("html")) {
if ($(elem).is("div.findme")) {
found = true;
break;
}
elem = $(elem).parent();
console.log(elem);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="findme">
<table>
<tr>
<td>
<img id="image" src="image.png" onclick="findTheDiv(this)" />
</td>
</tr>
</table>
</div>
Run the snippet, have your JavaScript console open and see what it logs.
the jQuery closest function already provides the feature you are looking for, no need to reinvent the wheel:
function findTheDiv(e) {
var res = $(elem).closest('div.findme')
if (res. length) {
console.log('found it', res)
return true
}
console.log('the image is not inside a `div.findme`')
return false
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="findme">
<table>
<tr>
<td>
<img id="image" src="image.png" onclick="findTheDiv(this)" />
</td>
</tr>
</table>
</div>

Get Value of Span Element that was changed before by JavaScript

i am developing a gadget and i am using JavaScript to change innerHTML of span, but after some operations i need to read that value. Additionally i am using pre-entered value for spans but when i try to read new data function loads pre-entered one.
Is there any solution for that?
JS:
function read_write(condition,filename){
var fso = new ActiveXObject('Scripting.FileSystemObject');
var fh = fso.OpenTextFile(System.Gadget.path+'\\'+filename+'.txt',condition, true,-2);
if (condition == 1) {
var result = fh.ReadLine();
return result;
}
else if (condition == 2) {
var spn1 = document.getElementById('span1').innerHTML;
fh.WriteLine(spn1+','+document.getElementById('span2').innerHTML);
}
fh.Close();
}
HTML:
<table id="sonuc">
<tbody>
<tr>
<td style="width:50%" valign="top">
<span class="result" id="span1"></span><br/>
<span class="result" id="span2"></span>
</td>
</tr>
</tbody>
</table>
If you're using innerHTML to write to the span element, you should be able to use it again to read. How are you trying to read until now?

Categories