简体   繁体   中英

How do i get textfield value in nativescript

i'm trying to get the text from my textfield in nativescript core.

let textField = args.object;
const yourSearch = textField.getViewById("requiredSkill").text;

the error i get is: cannot read property 'text' of undefined

please help

NativeScript View XML TextView

<TextView editable="true" id="requiredSkill"></TextView>

A simple button with tap event

<Button text="Button" tap="{{ onButtonTap }}" />

The JavaScript code behind for that tap event

var viewModel = observableModule.fromObject({
   onButtonTap: function (btargs) {
     let srcButton = btargs.object;
     const yourSearch =  srcButton.page.getViewById("requiredSkill").text;
   }
});

getViewById should be used on the <Page> model to search the entire page
or you must have a container/layout which should have an id, first find the layout using getViewById then again do another getViewById within that layout to find the TextView

so to answer your question, if it is a button click event, get the button and get the page of the button and find the view by Id

srcButton.page.getViewById

Thanks @Dickens, I am adding a specific example for NativeScript playground :

home-page.js:

var HomeViewModel = require("./home-view-model");
var homeViewModel = new HomeViewModel();

function pageLoaded(args) {
  var page = args.object;
  page.bindingContext = homeViewModel;
}

exports.pageLoaded = pageLoaded;

home-page.xml:

<Page loaded="pageLoaded" xmlns="http://www.nativescript.org/tns.xsd">
  <ActionBar title="Home">
    </ActionBar>
    <ScrollView>
        <StackLayout orientation="vertical" width="210" height="210"
            backgroundColor="lightgray">
            <TextField id="uspas" hint="Enter text..."  text="aaa,bbb"/>
            <Button text="Login" tap="{{ login }}" />
        </StackLayout>
    </ScrollView>
</Page>

home-view-model.js:

var observableModule = require("tns-core-modules/data/observable");

function HomeViewModel() {
  var viewModel = observableModule.fromObject({
    login: function (buttonArguments) {
      let srcButton = buttonArguments.object;
      const testo = srcButton.page.getViewById("uspas").text;
      var uspasCouple = testo.split(",");
      us = uspasCouple[0];
      pas = uspasCouple[1];
      console.log("Hai scritto:", us, pas);
    },
  });

  return viewModel;
}

module.exports = HomeViewModel;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM