Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you get the html and value output to a string

given this html input element, <input id="input1" type="text" />

if the user enters a value of 'test', is there a way in jQuery to serialize that to a string?

The output I would be looking for is, <input id="input1" type="text" value="test" />

I am not copying this to another element in DOM, I need the actual string so I can send it to EVOPdf. I've already tried the clone(true), but it doesn't give me any values the user has entered into the inputs.

I'm resigned to having to parse the html() string and insert a value for each input unless someone knows a better way.

like image 748
edepperson Avatar asked Nov 04 '22 11:11

edepperson


1 Answers

I my testing, it turns out that the attribute value has nothing to do with the value value - at least in my testing with Safari 5.1 and FF 6.

So, if I modified the contents of a text field (I typed ueoau) and select it

> var text = $('input[type=text]').first()

and get its value using .val()

> text.val()
"ueoau"

but getting it's markup gets the value rendered as empty(this snippet from james' answer)

> $('<div>').append(text.clone()).remove().html()
"<input autocomplete="off" name="q" class="textbox" placeholder="search" tabindex="1" type="text" maxlength="140" size="28" value="" style="width: 200px; max-width: 200px; ">"

getting the attribute value also doesn't work(using the DOM getAttribute here to avoid jQuery's magic in attr())

> text[0].getAttribute('value')
""

So again, the attribute value is not the same as the value value. So, one workaround you could use is setting its attribute to its value

> text[0].setAttribute('value', text.val())
> $('<div>').append(text.clone()).remove().html()
"<input autocomplete="off" name="q" class="textbox" placeholder="search" tabindex="1" type="text" maxlength="140" size="28" value="ueoau" style="width: 200px; max-width: 200px; ">"

Which worked for me. I guess my explanation for this is that the attribute value only stands for the initial value of the field, and is not synced with its true value afterwards.

like image 109
airportyh Avatar answered Nov 14 '22 04:11

airportyh