Building an element with jQuery gets me an error - javascript

I am trying to make an element with jQuery, which contains text from an input field after the user clicks the SUBMIT button.
Here is my jsfiddle: http://jsfiddle.net/2y26rzot/
Here is my javascript:
$(document).ready(function () {
$('button[type=submit]').click(function () {
var typedText = $('input[type=text]').val();
var resultText = $('<p></p>').text(typedText+'2');
$('section.result').append(resultText);
console.log(typedText);
alert(typedText);
console.log(resultText);
alert(resultText);
});
});
I have included bootstrap js and css and of course jQuery as well.
The problem occurs somewhere between the first and the second alert, but I have no idea where and why. I have basic understanding of jQuery, as I learned it by doing, so I may be getting something wrong here.
The error on my local machine reads:
text
index.html:45 [p, jquery: "1.11.0", constructor: function, selector:
"", toArray: function, get: function…]
Navigated to file:///C:/Users//Desktop/textonbackground/index.html?
Of course if I remove the last 2 lines with the resultText console log and alert I don't get an error, but the text still vanishes and I don't understand why. Can someone explain this to me and of course suggest some other way to achieve my goal, namely to get information from the input field and post it as a paragraph on the page.
I should mention that I've tried different approaches building the variables and appending the text (with .add and .after) but nothing changed. I am missing something here.
Your help is much appreciated!

The text disappears because the page refreshes after form submission. The problem is not in .text()
If you add e.preventDefault() to it, the text will stay where it should.
If you don't want to change the event, you could use a regular button (<button type="button">) without the form
Online here: http://jsfiddle.net/2y26rzot/3/

Your code seems to work fine in the fiddle, you just need to prevent the default action of the form submitting (if it submits it will refresh the page and so your clientside changes, ie. the changes made with js, will not show):
$('button[type=submit]').click(function (e) {
e.preventDefault();
...rest of code
});
Updated Fiddle

If you want to append a p element, with a text inside, you should bascalliy do
var resultText = $('<p>'+typedText+'2</p>');
Because .text() returns either the text of the concerned element if you dont pass any argument (to get text), or the jquery object of the concerned element if you pass an argument (to set text)

Related

jquery validation plugin detects errors, but no messages appear, why not?

I'm using the jQuery Validator plugin 1.19.5 on a slightly large (but simple) form generated from a PDF by an online converter to html5
The form has a Submit button implemented as a button with onclick to a javascript function within the formviewer.js file that is part of the conversion to html5. If I open the form in Chrome 107.0.5304.107 Developer Tools, I can see that the Submit button goes to the following code that I added to the success branch of the function that handles the submit in formviewer.js:
success: function() {
const OSHform=$("form").eq(0);
if (OSHform.valid()) {
top.document.location.href = "/Adsentry/completed";
}
else {
alert("Fields did not validate, please fix errors and try again");
}
},
failure: function() {
alert("Form failed to submit, please try again")
}
In a separate script, I invoked validate() on the form element, passing it rules for the fields to validate.
var $j = jQuery;
var OSHform = $j("form");
OSHform.validate({
rules: {
"NAME OF DRIVER": "required",
"EMAIL": "required",
"EMAIL": "email",
"ADDRESS": "required"
}
});
If I omit required fields, or enter an invalid email address in an email field, the call to valid() returns false. And in fact, if I look at the input elements in the Elements tab, I can see that class="error" gets added, and if I correct the error it changes to class="valid". Additionally, with class="error", a label gets added for that element, also with class="error", and correcting the problem adds style="display:none;" to the label.
So everything is great, except that there is no text or message that goes with the label, so its presence/absence, or the presence/absence of display:none on it, has no effect on the normal display of the page.
I have tried stepping through the code in the debugger, but I'm afraid my javascript is so weak I can't really figure out what's going on to the extent of understanding why the messages are not being displayed.
You can play with it live here for the time being, but I can't promise to stop fiddling with it! There are currently only 3 required fields: Name of driver, Address, and Email. If they are all correct, the form submits as intended.
A little disappointed that this didn't even get any comments, let alone answers. On the other hand, it turned out the answer was exactly as anyone even slightly more experienced than me would likely have guessed: errors were being reported in HTML elements, but there was no CSS to put them in the right location on the page. The plugin seemed to be buggy in failing to produce default message text describing the errors; instead, it just produced message text that was simply the name attribute of the erroneous input element. But without appropriate CSS, that name attribute was output in the black strip at the bottom of the page, making it essentially invisible. It took a sharp eye to notice the sudden appearance of "fly specs" at the bottom of the page when clicking the submit button.
The plugin just inserts an HTML element into the DOM immediately following the bad input element. But the files generated from the PDF include a style sheet with selectors using the ID of each input element to give the input element absolute placement on the page. And simply inserting an element into the DOM as the next sibling of the input element, without a style, results in having it rendered at the bottom of the page. Even when I figured out that the lack of CSS was the problem, it took me a while to get something that worked: good old selector specificity in action. All of the input elements were placed using ID selectors with absolute position, and I could find no way to have the simple next-sibling relationship of the message to the input element cause the message to be rendered immediately after the input element. Although it made me feel "icky" to do it, the solution I came up with was to use jQuery to iterate over all the message elements with the "error" class, get the ID of the input element it was reporting, and then use $.css() to get the input element's effective top, left, and width style attributes. Then strip off the trailing "px", multiply by 1 to get a numeric value, add the width to the left numeric value, and specify new top and left attributes using $.css() on the message elements. This put the messages I defined in the messages sub-object of the object passed to the validate constructor appear in the right locations. It only remains a mystery why the default messages didn't appear instead of the names of the input elements for elements that were invalid.

Spotfire Document Property setting using JS

I have created JS script that capture user inputs and publish them in another hidden input document.
I confirmed it works because I made the hidden input visible and publish all the input as delimited string.
So far it works fine
but when I try to use the property document in another textarea, ironpython etc.. within the same DXP it is returning blank, even though I can see the string published in the previous text area.
I used this html tags ...
for input property to display the captured data.
jQuery to capture all the inputs
inval=$.....
......
....
then used this to publish them in the input field $('#dfdklsfksldfkslfs').text(inval).blur()
so far all works fine.
but after this when trying to use the document property in textarea, irontpython, within the same DXP, it is returning (BLANK) even though I can see them published in the textarea.
am I missing any steps? do I need to reassign some features?
also I have tried $('#dfdklsfksldfkslfs').val(inval).blur() this won't even publish the data in the inputfield.
here is the update with code
html
<div id='dispInput'> <spotfirecontrold id='dfdklsfksldfkslfs'></div>
jquery
$('button')click(function(){
inval=$('input').map(function(){
return $(this).val(); }).get().join('-');
$('#dfdklsfksldfkslfs').text(inval).blur() //this publish the result but don't assign the data to the document property
})
I am completely lost.
thanks a lot
Try setting timeout in the function (500ms will do).
$('button')click(function(){
setTimeout(function (){
inval=$('input').map(function(){
return $(this).val(); }).get().join('-');
$('#dfdklsfksldfkslfs').text(inval).blur()
}), 500
});
Hope this helps.

How to output a link in an input field via a prompt?

I am struggling with this and can't get it to work. I am using jQuery to click on a link that will open me a prompt. In this prompt, I want the user to add a URL to link it to some other websites. That works fine, but I can't get the value of the prompt to be shown properly in the input field.
The error I am getting after adding my text in the prompt is the fact
that it outputs it like [Object object].
I do know how to do this in plain JS, but not in jQuery and I need jQuery.
This is my code:
$(".html-button").on("click", function () {
var urls = prompt("Add a link", "http://");
var setText = $("#post-text").val().append('<a href="'+ urls + '"</a>');
// Adding prompt text into my input field
$("#post-text").val(setText);
});
I thought I could do this by using append instead of innerHTML, which I would use in plain JS... Can someone help please?
PS: preferably I would not want to output the anchor already in my input field, but only after submitting the post, but this is a nice to have.
Edit: Fiddle link
You seem to have mixed up some variables here. You are assigning the value of the prompt response to var urls, but then expecting it to be in an undefined var person (guessing you've used the example for this from the W3 Schools Tutorial (https://www.w3schools.com/jsref/met_win_prompt.asp)).
Assuming that your input element has an id of post-text - then you would do this:
$("#post-text").val(urls);
I am working on the assumption here that you're writing the URL into an input field, as you suggest. If you want those a tags in the input field as well then it would be:
$("#post-text").val('<a href="' + urls + '"</a>');
If your intention is to output it as a link somewhere including the HTML 'a' tags so it can be clicked, then you'd need to append it to an appropriate element (not a input field) in the right place in the DOM/on the page.
Lastly, if you want to write the value into the field after the form as been submitted (for whatever reason) you could either store it in a variable and write it on submit, or perhaps in a hidden field. I am unsure why you would want to do this though.
Hope this helps.

Warn user when form contains unsaved data, ignoring data table filter fields

I'm searching for a way to warn the user that inside the form is unsaved data.
The warning should appear if the user navigates to another site or if he closes the browser.
I found this solution which kind of works. Sometimes it does not react if browser gets closed.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
// Set the unload message whenever any input element get changed.
$(':input').change(function() {
setConfirmUnload(true);
});
// Turn off the unload message whenever a form get submitted properly.
$('form').submit(function() {
setConfirmUnload(false);
});
});
function setConfirmUnload(on) {
var message = "You have unsaved data. Are you sure to leave the page?";
window.onbeforeunload = (on) ? function() { return message; } : null;
}
</script>
Now I have one Problem.
I've got a <p:datatable> on my page. Each column has a filter field. Since this field is also a input field the selector also matches if something is in the filter field.
Is it possible to avoid that the selector checks the filter fields.
The selector you are looking for is :input:not(.ui-column-filter) (data table filter inputs have a ui-column-filter class). You can simply inspect those fields in your browser and see what classes are set. In Chrome right-click a field and select "Inspect".
So change this line:
$(':input').change(function() {
to:
$(':input:not(.ui-column-filter)').change(function() {
You can test both selectors in your JavaScript console and see the difference.
See also:
https://api.jquery.com/category/selectors/
https://api.jquery.com/not-selector/
Additionally, you should eliminate the script that loads jQuery. jQuery is bundled with PrimeFaces and is loaded when when you use PrimeFaces components on a page. Multiple instances of jQuery will cause uncaught type errors.
You can write a more specific selector instead of $(':input')
If the datatable is not inside the form tag you can do something like $('form :input'). Or you can use the .not() method to exclude specific elements.

Passing TextBox Value to a unique label?

I am just getting into Jquery and I am stuck on a little bit of a bug. In my HTML I generate some H tags and Labels. These H tags and Labels have an on click function that will take that element whether it be an H tag or Label and pass it off to a method (setProperties(this)).
This method will capture what was written inside the input field and assign it to that element. My bug is that after I click on 2 elements it will change to whatever was in the input on both. I am assuming the elements are now listening to the input field and assigning there text value to what was inside the input field. I am curious on how I could rearrange my code to make what ever you element you click on. That field will be the unique field to change.
Variables :
Element is the element I click on such as a H tag or Label
the id ChangeText is the input element where you type to change the label or H tags value.
function inputfield(element){
$("#changeText").on("blur",function(){
$(element).text($("#changeText").val());
});
}
Here is a Jfiddle of what my problem is. If you click on two of the test texts and then change the value of the input. It will change both. I am looking to change only one.
http://jsfiddle.net/QMsQq/5/
It appears that when the inputfield function is called, you are setting the onblur to fire.
The on function will last after the inputfield function call. Try calling "off" to remove prior set on events from changeText.
function inputfield(element){
$("#changeText").off().on("blur",function(){
$(element).text($("#changeText").val());
});
}
Warning: untested code.
http://jsfiddle.net/QMsQq/6/ Updated your fiddle to show my solution
Assign the element to a variable.
var $elem = $('whatever');
and pass that as the argument. And I think you want to fire on focus of an element (click).
Also, here is a VERY simple vanilla js example of what I think you're getting at:
http://jsfiddle.net/Lqf25/3/
Hopefully that helps a smidge.
Edit:
ok, for your fiddle:
Your input syntax is jacked. (missing '>' and you don't need '/input' anyway)
Don't use (onClick) in html. Separate your concerns - javascript goes in the script file, not inline. See my fiddle for an example. Although, from reading your latest posts I don't think it's quite what you want - I'm actually a little confused on what exactly you're trying to do...
Edit 2:
Try this: http://jsfiddle.net/w88xr/3/
I think that's what you're looking for.

Categories

Resources