1

I am trying to create a input element with a expected html output of this:

<input 
  type="text" 
  maxlength="13" 
  value="DD/MM/YY 00:00.0" 
  onkeypress="dateTime()"
>

I tried doing this with the following jQuery code

var input = $("<input>",
  {
    name : newName,
    maxlength : newSize,
    size : newSize,
    type : 'text',
    value : newVal,
    onkeypress : dateTime()
  });

But I don't get the expected output

<input type="text" maxlength="13" value="DD/MM/YY 00:00.0">

Question 1 : what is the description of this code, because I cannot for the life of me find anything in the jQuery documentation about this stuff (link would be appreciated).

Question 2 : what is the correct parameter to use to get my expected html result?

6
  • 3
    What result do you expect? Commented Dec 15, 2013 at 17:27
  • Link would be appreciated -> what about jquery.com? Commented Dec 15, 2013 at 17:28
  • And where are those variables coming from? Commented Dec 15, 2013 at 17:29
  • What good is a link to jQuery if I don't know what the code is called? Commented Dec 15, 2013 at 17:29
  • @ComFreek the expected result is at the top please read carefully :) Commented Dec 15, 2013 at 17:30

2 Answers 2

1

try

onkeypress : "dateTime()"

instead of

onkeypress : dateTime()

that one executes the function.

var input = $("<input>",
  {
    name : newName,
    maxlength : newSize,
    size : newSize,
    type : 'text',
    value : newVal,
    onkeypress : dateTime
  });

or

input.on('keypress',dateTime);

In the callback, "this" represents the event target (input).

You can get values from the input by using $(this).val(); $(this).attr('myattribute'); $(this).data('myvar');

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, what is called in jQuery so I can search documentation to know what the accepted parameters are
The jQuery method is called ;-) api.jquery.com/jQuery/#jQuery-html-attributes Any parameter is acceptable. They will be placed as html attributes. Edited answer for jQuery 1.4. See doc for 1.8+
If I cannot use (), how do I pass parameters to a function this way? e.g. dateTime("DD/MM/YYYY")?
You don't. You can add data attributes to the elements ({"data-myvar": 12}) and get the values back in dateTime() with $(this).data('myvar')
1

Suggest you need to review the keypress docs on jquery:

http://api.jquery.com/keypress/

You need to look at how to use document ready event in jquery too and how the selector engine works. Your code should look a bit like this:

$(function() {
    $("input").keypress(function() {
         //do stuff
    })
})

1 Comment

What is the advantages of doing that over just a html attribute?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.